SFINAE for designers works in VC2017, but not in clang / gcc

#include <type_traits> template<bool b> struct S { template<typename = std::enable_if_t<b>> S() {} template<typename = std::enable_if_t<!b>> S(int) {} }; S<true> s{}; // error in clang/gcc, OK in VC2017 S<false> s{0}; // error in clang/gcc, OK in VC2017 

In both cases, clang / gcc tries to create an instance of ctor, which should actually be dropped due to SFINAE. Error message:

error: there is no type named 'type' in 'std :: enable_if <false, void>'; "enable_if" cannot be used to disable this declaration

clang / gcc instance of another ctor is incorrect, since it should not be in the list of possible overloads, right?

But before I write a mistake, I would like to read what others think. Maybe I do not understand ...

+5
source share
2 answers

This is an error in MSVC; clang and gcc are right.

The problem is that SFINAE only happens when overload resolution is allowed, not earlier. I mean, if a function is poorly formed even before you called it, this is a mistake.

If you use S<true> , for example, an instance of the entire class is created. It will look something like this:

 struct S_true { template<typename = void> S() {} template<typename = /*fail*/> S(int) {} }; 

As you can see, the second constructor is completely poorly formed, it is not a correct definition, because there is no type found (due to std::enable_if ). So SFINAE can't even hit, the class definition is poorly formed and diagnosed.

You need to make the template parameter b part of the list of template parameters for both constructors (look at @bolov answer).

+11
source

@ Rakete1111 is 100% right.

You need to make the template parameter bool b part of the template parameter list of both constructors.

Here's how to do it (this is a pretty standard technique):

 template<bool b> struct S { template<bool bb = b, typename = std::enable_if_t<bb>> S() {} template<bool bb = b, typename = std::enable_if_t<!bb>> S(int) {} }; 
+6
source

Source: https://habr.com/ru/post/1272389/


All Articles