【发布时间】:2014-02-08 23:00:59
【问题描述】:
我有一个类模板,它有两个参数,一个是类型名称,另一个是布尔值,用于确定如果遇到错误,类是否会抛出异常。
MyClass.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
}
};
main.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
【问题讨论】:
-
'是在每次实例化时创建的模板类中每个方法的新版本' 是的,对于任何实例化的签名变体,它们都是实际使用的。这就是 SFINAE 如此有用的原因......
-
SFINAE?我以前听说过它,但不太确定它是什么或它是如何工作的
标签: c++ class templates instantiation