Select class constructor using enable_if

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

Consider following code:

#include 
#include 

template 
struct A {
    int val = 0;

    template 

        
相关标签:
3条回答
  • 2020-12-01 00:25

    I think this can't work with a single defaulted template parameter, because its value needs to be resolved when the class template is instantiated.

    We need to defer the substitution to the point of constructor template instantiation. One way is to default the template parameter to T and add an extra dummy parameter to the constructor:

    template<typename U = T>
    A(int n, typename std::enable_if<U::value>::type* = 0) : val(n) { }
    
    0 讨论(0)
  • 2020-12-01 00:35

    Usually this is done using an anonymous defaulted argument :

    A(int n, typename std::enable_if<T::value>::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 <iostream>
    #include <type_traits>
    
    template <typename T>
    struct A {
        int val = 0;
    
        template<typename Integer
                ,typename  = typename std::enable_if<T::value && sizeof(Integer)>::type
                >
        A(Integer n) : val(n) {};
    
        A(...) {}
        /* ... */
    };
    
    struct YES { constexpr static bool value = true; };
    struct NO { constexpr static bool value = false; };
    
    int main() {
        A<YES> y(10);
        A<NO> 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

    0 讨论(0)
  • 2020-12-01 00:38

    With C++20

    You can achieve that simply by adding requires to the template:

    template <typename U = T> requires U::value
    A(int n) : val(n) { }
    

    The requires clause gets a constant expression that evaluates to true or false deciding thus whether to consider this method in the overload resolution, if the requires clause is true, or ignore it otherwise.

    Code: https://godbolt.org/z/CKTDFE

    0 讨论(0)
提交回复
热议问题