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

前端 未结 2 697
时光取名叫无心
时光取名叫无心 2021-01-20 04:41

Demo

A in class declaration of A::foo.

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

A::foo is now split by sfi

相关标签:
2条回答
  • 2021-01-20 05:18

    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)

    0 讨论(0)
  • 2021-01-20 05:25

    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));
    }
    
    0 讨论(0)
提交回复
热议问题