转载:https://www.jianshu.com/p/b56d59f77d53
没有真正的变量。模板元编程里所谓变量只是一个类型的别名符号,第一次绑定后就不能再变。如果想要保存一个变化后的值,只能重新定义一个新的变量。
它会占用更多的内存和运行时开销。纯函数式语言一般依赖编译器或者解释器对其进行优化,但是性能普遍还是没有命令式的好。这也是为什么大量地使用模板会使得C++的编译速度超出寻常地慢,而且会占用更多的内存
using Sum = __int(0); // ok
Sum = __add(Sum, __int(6)); // error
using Int0 = __int(0); // ok
using Sum = __add(Int0, __int(6)); // ok
惰性: 只有当你使用了模板的内部定义,编译器才会为模板生成对应的定义。
template<typename T>
struct ClonableCreator
{
static T* create(const T* instance)
{
return instance->clone();
}
};
template<typename T>
struct UnclonableCreator
{
static T* create(const T* instance)
{
return new T(*instance);
}
};
/* __if()元函数会根据第一个入参的bool值,对后面的两个参数中的一个进行求值。
因此当我们调用Creator<UnclonableObject, false>时,
__if(__bool(false), ClonableCreator<T>, UnclonableCreator<T>)
只会对UnclonableCreator<T>具现化,所以没有再出现之前的编译错误
*/
template<typename T, bool isClonable> using Creator =
__if(__bool(isClonable), ClonableCreator<T>, UnclonableCreator<T>);