How to use sfinae for selecting constructors?

后端 未结 5 1855
北海茫月
北海茫月 2020-11-29 04:24

In template meta programming, one can use SFINAE on the return type to choose a certain template member function, i.e.

template struct          


        
5条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 05:12

    The accepted answer is good for most cases, but fails if two such constructor overloads with different conditions are present. I'm looking for a solution in that case too.

    Yes: the accepted solution works but not for two alternative constructor as, by example,

    template ::type>
    explicit A(A const &);
    
    template ::type>
    explicit A(A const &);
    

    because, as stated in this page,

    A common mistake is to declare two function templates that differ only in their default template arguments. This is illegal because default template arguments are not part of function template's signature, and declaring two different function templates with the same signature is illegal.

    As proposed in the same page, you can go around this problem applying SFINAE, modifying the signature, to the type of a value (not type) template parameter as follows

    template ::type = true>
    explicit A(A const &);
    
    template ::type = true>
    explicit A(A const &);
    

提交回复
热议问题