在类模板的非模板化成员函数中使用enable_if

时间:2015-02-04 10:32:38

标签: c++ templates c++11 enable-if

我正在尝试使用非模板化成员函数f()定义类模板, 其中f()只有在类的模板为int时才允许调用。

#include <type_traits>

using namespace std;

template<typename T>
struct MyClass
{
    T f()
    {
        typename enable_if< is_same<T,int>::value >::type();

        return 0;
    };
};

int main()
{
    MyClass<int> x;

    MyClass<double> y;

    x.f();
    y.f(); // generates compile-time error
}

它有效,但它是一个好主意,还是最好使用常规解决方案?

std::enable_if to conditionally compile a member function

usage of enable_if for non-templated member function

Selecting a member function using different enable_if conditions

有替代方法吗?

[编辑]

问题在于,如果我使用标准技术,将通过以下代码允许通过y.f<int>()进行模板化函数调用:

#include <type_traits>

using namespace std;

template<typename T>
struct MyClass
{
    template<typename U = T>
    typename enable_if< is_same<U,int>::value, T >::type f()
    {
        T a = 1;

        return a;
    };

};

int main()
{
    MyClass<int> x;

    MyClass<double> y;

    x.f();
    y.f<int>();   // does not generate compile-time error
    y.f();        // generates compile-time error
}

0 个答案:

没有答案