gpt4 book ai didi

c++ - 限制类型模板参数仅采用特定模板的实例化

转载 作者:行者123 更新时间:2023-11-30 01:05:46 24 4
gpt4 key购买 nike

限制类型模板参数使其只接受特定模板实例化的惯用方法是什么?

例如,

template<typename P>
class C {
C() = default;
...
};

template<typename T>
class Accepted {
...
};

template<typename T>
class Other {
...
};

C<Accepted<float>> obj1; // should compile
C<Accepted<int>> obj2; // should compile
C<Other<int>> obj3; // should not compile
C<double> obj4; // should not compile

最佳答案

特化就是答案。

template<typename P> class C;

template<typename T>
class Accepted {
...
};

template<typename P>
class C<Accepted<P>> {
C() = default;
...
};

上面的任何C<Accepted<T>>格式良好,因为它在实例化时选择特化。而任何其他 C<T>选择未定义的主要特化,因此不会编译。

关于c++ - 限制类型模板参数仅采用特定模板的实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47967246/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com