C++是在每个实例化时创建的模板类中每个方法的新版本

标签 c++ class templates instantiation

我有一个类模板,它有两个参数,一个是类型名称,另一个是 bool 值,它确定遇到错误时该类是否会抛出异常。

我的类.h:

template<typename T, bool signal>
class MyClass {

    // methods which do not use or reference signal
    void Method1(args) {
        // some really long and complex code
    }
    void Method2(args) {
        // some more really long and complex code
    }

    // the method which checks the value of signal
    void throwMethod() {
        if (signal) throw (some exception); // if statement optimized away at compile time
    }
};

主要.cpp:

#include "MyClass.h"

void main(int argc, const char * argv[]) {
    MyClass<int, true> instThrow;
    MyClass<int, false> instNoThrow;

    // do something
}

但并不是这个类中的每个方法都会抛出异常,实际上只有两个函数实际检查信号的值,其余的根本不使用或引用这个参数。我的问题:类模板的每个方法(Method1、Method2)是否都为新实例重新创建,其中只有信号参数不同(如上所示)(大多数方法未使用)或者只是 throwMethod(实际使用参数)重新创建,如果是前者,则会导致不必要的 Method1 和 Method2 重复。

如果有什么不同,我的编译器是 Apple LLVM 编译器 3.0

最佳答案

这些方法是为您的代码使用的类型参数的每个变体生成的。为避免这种情况,您可以创建一个包含 Method1 和 Method2 的基类。基类只会将 T 作为模板参数,而上面的类只会继承它。

关于C++是在每个实例化时创建的模板类中每个方法的新版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21652875/

相关文章:

c++ - 为什么 "no match for ' operator <'"当我声明的时候?

c++ - 删除 char** 数组的正确方法

c++ - 能否将一个类简单地传递给 CUDA 内核以进行并行评估?

python - 使用变量调用类的属性

c++ - 线程池中的 boost::function 释放段错误

c++ - 从麦克风到整数数组的音频采样(C++/Qt)

C++ 虚拟覆盖函数链接器错误

java - 类似于 Enlive 的基于选择器的 Java 模板库

c++ - 给定一个类型,如何派生出通用的更宽类型(例如用于溢出安全求和)?

c++ - 如何避免由于内存不足导致的 gcc 崩溃