模板成员函数的外联sfinae可能吗?

时间:2017-05-06 08:00:22

标签: c++ c++11 templates sfinae

Demo

A :: foo的类声明。

struct A {
    template <typename T>
    void foo(T a); 
};

A :: foo现在由sfinae分开。

template <typename T>
typename std::enable_if<(sizeof(T) > 4), void>::type A::foo(T a ) {
    std::cout << "> 4 \n";
}

这不起作用。这是不允许的吗?

2 个答案:

答案 0 :(得分:3)

声明中的返回类型必须与定义匹配。

struct A {
    template <typename T>
    typename std::enable_if<(sizeof(T) > 4), void>::type
    foo(T a); 
};

SFINAE无法封装为实施细节。

demo

答案 1 :(得分:0)

实现这一目标的一种方法是内部标记发送:

#include <utility>
#include <iostream>

struct A {
    template <typename T>
    void foo(T a); 

    private:

    template<class T> 
    auto implement_foo(T value, std::true_type) -> void;

    template<class T> 
    auto implement_foo(T value, std::false_type) -> void;
};

template <typename T>
void A::foo(T a ) {
    implement_foo(a, std::integral_constant<bool, (sizeof(T)>4)>());
}

template<class T> 
auto A::implement_foo(T value, std::true_type) -> void
{
    std::cout << "> 4 \n";
}

template<class T> 
auto A::implement_foo(T value, std::false_type) -> void
{
    std::cout << "not > 4 \n";
}


main()
{
    A a;
    a.foo(char(1));
    a.foo(double(1));
}