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

时间:2016-03-03 02:14:55

标签: 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特化吗?

3 个答案:

答案 0 :(得分:0)

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

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();
    }

答案 1 :(得分:0)

解决此问题的一种常见方法是通过标记调度。我们可以在编译时生成不同的类型,以确定S::stat是否匹配AType - 并使用这些类型来调用不同的重载:

template <class S>
void foo() {
    foo_impl(std::is_same<decltype(S::stat), AType>{});
}

void foo_impl(std::true_type /* S::stat matches AType */) {
    // implementation 1
}

void foo_impl(std::false_type /* S::stat doesn't match AType */) {
    // implementation 2
}

答案 2 :(得分:0)

我无法使用decltype解决方案,因为我的编译器不支持它。

我能够利用foo_impl类解决方案,但只有当我将MyClass声明为:

class MyClass { public: typedef AType Stat; static const Stat stat = VAL; ... }

相关问题