Is out-of-line sfinae on template member functions possible?

℡╲_俬逩灬. 提交于 2019-12-01 21:45:41

The return type in the declaration must match the definition.

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

SFINAE cannot be encapsulated as an implementation detail.

(demo)

One way to achieve this is to internally tag-dispatch:

#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));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!