c++ - 基于静态成员类型的模板函数特化

标签 c++ templates template-specialization

我对模板没有太多经验,但我想知道以下情况是否可能。假设我们有一个带有静态成员 stat 的类 S。我可以使用 typeid 让它动态生成不同的代码:

    template <class S>
    void foo() 
    { 
        if (typeid(S::stat) == typeid(AType))
            implementation 1;
        else
            implementation 2;
    }

但是由于所有信息在编译时都是已知的,是否有可能为 S::stat 的类型 Atype 创建 foo 的特化?

最佳答案

您可能希望做这样的事情:

template<typename T> class foo_impl {

public:

    static void foo()
    {
          // This is your implementation 2
    }
};

template<> class foo_impl<AType> {

public:

    static void foo()
    {
          // This is your implementation 1
    }
};

template <class S>
    void foo() 
    {
        foo_impl<typename S::Stat>::foo();
    }

关于c++ - 基于静态成员类型的模板函数特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35761917/

相关文章:

c++ - 如何创建一个非常大的唯一整数数组?

c++ - 阵列超出范围MQL5循环

c++ - 遍历 function_traits 参数

html/templates - 用 <br> 替换换行符

c++ - 从 Swift 中的泛型参数继承的替代方法

c++ - 特化返回 void 且没有参数的成员函数

c++ - 如何在单独的视口(viewport)中使用帧缓冲区以及默认帧缓冲区?

constexpr 函数中存在 C++ Wconversion 警告,但模板中没有

c++ - 基于基类的特殊成员函数

c++ - 用于初始化模板类的静态数据成员的部分模板特化