Rozważmy następujący kod:Wybierz Konstruktor klasy używając enable_if
#include <iostream>
#include <type_traits>
template <typename T>
struct A {
int val = 0;
template <class = typename std::enable_if<T::value>::type>
A(int 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;
}
Chcę selektywnie zdefiniować konstruktora :: A (int) tylko dla niektórych typów korzystając enable_if. Dla wszystkich innych typów istnieje domyślny konstruktor A :: A (...), który powinien być domyślnym przypadkiem dla kompilatora, gdy podstawianie się nie powiedzie. Jednak ma to sens dla mnie kompilator gcc w wersji 4.9.0 (20130714) jest nadal narzeka
sfinae.cpp: In instantiation of 'struct A': sfinae.cpp:19:11:
required from here sfinae.cpp:9:5: error: no type named 'type' in
'struct std::enable_if'
A(int n) : val(n) {};
Czy coś jak to możliwe dla konstruktora? Czy jest to możliwe z innymi konstruktorami (copy-constructor i move-constructor)?
Czy może to być klasa fabryka pomocników? –