我有一个类模板,它有两个参数,一个是类型名称,另一个是 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/