具有替代返回类型的模板专业化

时间:2017-07-18 10:03:00

标签: c++ c++03

我有一个类模板成员函数,我需要创建一个因返回类型而异的特化。但这是不允许的。

template<typename Type>
class Class {
    Type Method(Type Argument) {...}
};

template <>
double Class<int>::Method(int Argument) {...}

你能建议一个解决方法吗? (目的是隐藏int的模板化定义。)

2 个答案:

答案 0 :(得分:4)

让我们讨论问题的根源。当您为类模板专门化成员函数时,它会导致实例化类的声明。因此,您的专业类外定义与生成的声明冲突。

一种可能的解决方案是添加一个间接层。不要按原样对返回类型进行硬编码,而是在模板参数上间接使依赖,比如来自traits类。

这样的事情:

template<typename T>
struct ClassMethodReturn { typedef T type; };

template<>
struct ClassMethodReturn<int> { typedef double type; };

template<typename Type>
class Class {
    typedef typename ClassMethodReturn<Type>::type ret_type;
    ret_type Method(Type Argument) { return ret_type(); }
};

template <>
double Class<int>::Method(int Argument) { return 0.0; }

因此,您可以轻松地控制每个专业化的返回类型。

答案 1 :(得分:1)

以下是使用std::enable_if的另一种解决方法。

template<typename Type>
class Class {
    public: 
    template <typename TypeDat=Type> std::enable_if_t<std::is_same<TypeDat,int>::value,double> Method(Type Argument) {
        std::cout<<"case 1"<<std::endl;    
    }
    template <typename TypeDat=Type> std::enable_if_t<!std::is_same<TypeDat,int>::value,Type> Method(Type Argument) {
        std::cout<<"case 2"<<std::endl;
    }

};
int main() {
    Class<int> a;
    a.Method(5);   //print case 1
    Class<char> b;
    b.Method('c'); //print case 2
}

Demo

就个人而言,我喜欢StoryTeller的解决方案。

相关问题