Why compile error with enable_if

前端 未结 5 1923
小蘑菇
小蘑菇 2020-12-09 07:50

Why this does not compile with gcc48 and clang32?

#include 

template  
struct S {

    template 
    typename         


        
5条回答
  •  温柔的废话
    2020-12-09 08:35

    To get std::enable_if to work like this, you are relying on SFINAE. Unfortunately, at the point where you declare

    S<1> s1;
    

    it will instantiate all of S<1>'s member declarations. SFINAE will only come into play at this point if S<1> were an ill-formed construct. It is not. Unfortunately, it contains a function which is invalid, thus the instantiation of S<> is invalid.

    For things like this, I might defer to a seperate template struct:

    template 
    struct f_functor {
        template 
        static int f(T t) { return 1; }
    };
    
    template <>
    struct f_functor {
        template 
        static int f(T t) { return 2; }
    };
    
    template  
    struct S {
    
        template 
        typename int f(T t) { return f_functor::f(t); }
    };
    

提交回复
热议问题