C++ 模板

模板元编程

参考:《Effective C++》。

模板是编译期多态。
模板元编程(Template metaprogramming, TMP)是编写 template-based C++ 程序并执行于编译期的过程。所谓模板元程序(Template metaprogram)是以 C++ 写成、执行于 C++ 编译器内的程序。一旦 TMP 程序结束执行,其输出,也就是从 templates 具现出来的若干 C++ 源码,便会一如既往地被编译。

优缺点

优点:

  • 多态:一次定义,多处实例化;
  • 模板元程序执行于编译期,也就是将运行期的错误前移到了编译期;
  • 高效:较小的可执行文件、较短的运行期、较少的内存需求。

缺点:

  • 编译时间变长了。

情景1:定义在 h 文件

  • File: SourceFile.h
#ifndef SOURCEFILE_H
#define SOURCEFILE_H

#include <iostream>

class SourceFile {
public:
    template<typename T>
    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 <iostream>

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

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

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

// Explicit instantiations
// 如果定义在 cpp 文件中,必须在 cpp 文件显式实例化模板构造函数
// 否则报错:
// undefined reference to `SourceFile::SourceFile<int>(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<float>(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 <iostream>

template<typename T>
void func(T x );

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

template<typename T>
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 文件,并且调用对应的模板函数/类时,编译器就得知了怎么去实例化模板,故在编译期对应的模板就已经被实例化了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值