Constructor conditionally marked explicit

前端 未结 2 1265
借酒劲吻你
借酒劲吻你 2020-12-08 19:30

Update: conditional explicit has made it into the C++20 draft. more on cppreference

The cppreference std::tuple constructor page has a bunch of C++1

2条回答
  •  温柔的废话
    2020-12-08 20:15

    The proposal that added that N4387: Improving pair and tuple, revision 3 has an example of how it works:

    Consider the following class template A that is intended to be used as a wrapper for some other type T:

    #include 
    #include 
    
    template
    struct A {
      template::value &&
          std::is_convertible::value
        , bool>::type = false
      >
      A(U&& u) : t(std::forward(u)) {}
    
     template::value &&
          !std::is_convertible::value
        , bool>::type = false
      >
      explicit A(U&& u) : t(std::forward(u)) {}
    
      T t;
    };
    

    The shown constructors both use perfect forwarding and they have essentially the same signatures except for one being explicit, the other one not. Furthermore, they are mutually exclusively constrained. In other words: This combination behaves for any destination type T and any argument type U like a single constructor that is either explicit or non-explicit (or no constructor at all).

    As Praetorian points out this is exactly how libstdc++ implements it.

    If we modify the OPs example accordingly, it also works:

    struct S {
      template ::value, bool>::type = false>
      S(T) {}
    
      template ::value, bool>::type = false>
      explicit S(T) {}
    };
    

提交回复
热议问题