限制类型模板参数使其只接受特定模板实例化的惯用方法是什么?
例如,
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/