Select class constructor using enable_if

前端 未结 3 1758
庸人自扰
庸人自扰 2020-12-01 00:18

Consider following code:

#include 
#include 

template 
struct A {
    int val = 0;

    template 

        
3条回答
  •  春和景丽
    2020-12-01 00:35

    Usually this is done using an anonymous defaulted argument :

    A(int n, typename std::enable_if::type* = 0) : val(n) {};
    

    You can not use template parameters from the class to SFINAE out methods. SO one way is to add a dummy type replacing int :

    see: http://ideone.com/2Gnyzj

    #include 
    #include 
    
    template 
    struct A {
        int val = 0;
    
        template::type
                >
        A(Integer n) : val(n) {};
    
        A(...) {}
        /* ... */
    };
    
    struct YES { constexpr static bool value = true; };
    struct NO { constexpr static bool value = false; };
    
    int main() {
        A y(10);
        A n;
        std::cout << "YES: " << y.val << std::endl
                  << "NO:  " << n.val << std::endl;
    }
    

    This works because you use a member template parameter to SFINAE out the constructor but the test is always true so it doesn't pollute your checks

提交回复
热议问题