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

Demo

A in the class declaration A :: foo.

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

      

A :: foo is now split into sfinae.

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

      

This does not work. Is this not allowed?

+3


source to share


2 answers


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 )

+3


source


One way to achieve this is by sending tags internally:



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

      

0


source







All Articles