我正在写一个代理类型的类。我想要该类的两个变体:
Proxy<SomeType> something;
这将使用默认构造函数初始化
something
,并:Proxy<SomeType, SomeValue> something;
这将使用
something
初始化SomeValue
。第二种形式可以定义为:
template<typename T, T init>
class Proxy {...};
我不知道的是如何编写“没有初始化程序”的特化知识。
最佳答案
在主模板中使用T
值的参数包。在第一个特化包中,它是空的,在第二个特化包中,它只有一个初始值:
template<class T, T ...>
struct Proxy;
template<class T>
struct Proxy<T> {
void foo() { std::cout << "no init value" << std::endl; }
};
template<class T, T Value>
struct Proxy<T,Value> {
T mVal{Value};
void foo() { std::cout << mVal << std::endl; }
};
int main() {
Proxy<int> f;
Proxy<int,123> f2;
f.foo(); // no init value
f2.foo(); // 123
Demo
关于c++ - 非类型参数上的模板类的部分特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60820817/