How to use sfinae for selecting constructors?

后端 未结 5 1849
北海茫月
北海茫月 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:13

    With C++20 you can use the requires keyword

    With C++20 you can get rid of SFINAE.

    The requires keyword is a simple substitute for enable_if!

    Note that the case where otherN == N is a special case, as it falls to the default copy ctor, so if you want to take care of that you have to implement it separately:

    template struct A {
       A() {}    
    
       // handle the case of otherN == N with copy ctor
       explicit A(A const& other) { /* ... */ }
    
       // handle the case of otherN > N, see the requires below
       template requires (otherN > N)
       explicit A(A const& other) { /* ... */ }
    
       // handle the case of otherN < N, can add requires or not
       template
       explicit A(A const& other) { /* ... */ }
    };
    

    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 the method is preferred over another one that has no requires clause, as it is more specialized.

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

提交回复
热议问题