c++ - 部分模板特化仅限于某些类型

标签 c++ templates template-specialization typetraits

是否可以编写仅用于类类型的部分模板特化,例如,从特定类继承或遵守可以通过类型特征表达的某些其他约束? 即,像这样:

class A{}

class B : public A{}

template<typename T>
class X{
    int foo(){ return 4; }
};

//Insert some magic that allows this partial specialization
//only for classes which are a subtype of A
template<typename T> 
class X<T>{
    int foo(){ return 5; }
};

int main(){
    X<int> x;
    x.foo(); //Returns 4
    X<A> y;
    y.foo(); //Returns 5
    X<B> z;
    z.foo(); //Returns 5
    X<A*> x2; 
    x2.foo(); //Returns 4
}

最佳答案

通常如果你想要条件部分模板特化,你需要提供一个额外的参数,然后使用 enable_if:

template<typename T, typename=void>
class X {
public:
    int foo(){ return 4; }
};

template<typename T>
class X<T, std::enable_if_t<std::is_base_of_v<A, T>>> {
public:
    int foo(){ return 5; }
};

关于c++ - 部分模板特化仅限于某些类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12161033/

相关文章:

c++ - 获取发送到 std::cout 的最后一个字符

c++ - 在实例上调用时未找到模板类中的模板成员函数

c++ - 这是部分功能模板特化吗?

C++ 函数模板特化声明和模板参数;无与 <> 与 <类型>

c++ - 创建 N 个零的索引序列

c++ - 变量名的长度是否会产生任何与性能或效率相关的问题?

c++ - 错误 : anachronistic old-style base class initializer

c++ - Xcode 不使用 gtest 框架编译,但是可以看到它

templates - Polymer - DOM 树中元素数据的 dom 重复和缓存

django 文件上传不起作用