c++ - 非类型参数上的模板类的部分特化

标签 c++ templates

我正在写一个代理类型的类。我想要该类的两个变体:

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/

相关文章:

C++ 在二叉搜索树中删除

c++ - 安装qt-creator不运行

c++ - 模板特化问题

C++ 模板元编程静态类型检查

c++ - 这个模板到底检查了什么?

c++ - 带有 Crypto++ 库的 QT 控制台应用程序

c++ - 用 unique_ptr 初始化 std::vector

c++ - isdigit() 和 isalnum() 给出错误,因为输入是 const char 并且无法转换。其他可能查看输入是否为数字的方法?

templates - 编程语言中的元函数和元类是什么意思?

非模板类中任意类型的C++成员变量