栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ 模板

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ 模板

情景1:定义在 h 文件
  • File: SourceFile.h
#ifndef SOURCEFILE_H
#define SOURCEFILE_H

#include 

class SourceFile {
public:
    template
    SourceFile(const char* name, T val) {
        std::cout << "SourceFile constructor" << std::endl;
    }
};

#endif // SOURCEFILE_H
  • File: main.cc
#include "SourceFile.h"

int main() {
    SourceFile sf("1.txt", 10); // Compiled OK!

    return 0;
}

此时,模板函数不需要实例化。

情景2:定义在 cpp 文件
  • File: SourceFile.h
// File: SourceFile.h
#ifndef SOURCEFILE_H
#define SOURCEFILE_H

#include 

class SourceFile {
public:
    template
    SourceFile(const char* name, T val);
};

#endif // SOURCEFILE_H
  • File: SourceFile.cc
#include "SourceFile.h"

template
SourceFile::SourceFile(const char* name, T val)  {
    std::cout << "SourceFile constructor" << std::endl;
}

// Explicit instantiations
// 如果定义在 cpp 文件中,必须在 cpp 文件显式实例化模板构造函数
// 否则报错:
// undefined reference to `SourceFile::SourceFile(char const*, int)'
template SourceFile::SourceFile(const char* name, int val); // Required!
  • File: main.cc
#include "SourceFile.h"

int main() {
    SourceFile sf("1.txt", 10); // Compiled OK!
    
    // ld error:
    // undefined reference to `SourceFile::SourceFile(char const*, float)'
    SourceFile sfd("2.txt", 1.0f); // ld error!

    return 0;
}

此时,必须在 SoureFile.cc 中显式实例化模板函数。

示例

除了模板构造函数,一般模板函数也是如此:

  • File: some.h
#ifndef SOME_H
#define SOME_H

#include 

template
void func(T x );

#endif // SOME_H
  • File: some.cc
#include "some.h"

template
void func(T x) {
    std::cout << "func("  << x << ")" << std::endl;
}

// Explicit Initilizations
template void func(int x);
  • File: main.cc
#include "some.h"

int main() {
    func(20); // OK!
    func(10.0); // ld ERROR!

    return 0;
}
原因分析

cpp 文件是单独编译的。模板类/函数没有生成真正的类/函数的实体(不是指对象实体),必须要在编译期决定。但是,如果模板的定义写在 some.cc 文件中,却没有实例化模板,这就导致 some.o 中没有对应的实体的定义。那么,当 main.o 在连接阶段去寻找真正的模板对应的类/函数的实体定义时会出错。

相反,如果定义直接写在 h 文件中,当 main.cc include 这个 h 文件,并且调用对应的模板函数/类时,编译器就得知了怎么去实例化模板,故在编译期对应的模板就已经被实例化了。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/847138.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号