Das Buch von Stroustrup gibt ein Beispiel zur Beantwortung der Frage: "Ist es möglich, vom Typ X
aufzurufen" (Abschnitt 28.4.4 "Weitere Beispiele mit Aktivieren_if "). Ich habe versucht, das Beispiel zu reproduzieren, habe aber etwas falsch gemacht und kann nicht verstehen, was.Test, ob der Aufruf von f (x) mit Metaprogrammierung möglich ist
In meinem Code unten gibt es eine Funktion f(int)
. Ich erwarte, dass dann das Ergebnis von has_f<int>::value
1
(true
) ist. Das tatsächliche Ergebnis ist 0
(false
).
#include <type_traits>
#include <iostream>
//
// Meta if/then/else specialization
//
struct substitution_failure { };
template<typename T>
struct substitution_succeeded : std::true_type { };
template<>
struct substitution_succeeded<substitution_failure> : std::false_type { };
//
// sfinae to derive the specialization
//
template<typename T>
struct get_f_result {
private:
template<typename X>
static auto check(X const& x) -> decltype(f(x));
static substitution_failure check(...);
public:
using type = decltype(check(std::declval<T>()));
};
//
// has_f uses the derived specialization
//
template<typename T>
struct has_f : substitution_succeeded<typename get_f_result<T>::type> { };
//
// We will check if this function call be called,
// once with "char*" and once with "int".
//
int f(int i) {
std::cout << i;
return i;
}
int main() {
auto b1{has_f<char*>::value};
std::cout << "test(char*) gives: " << b1 << std::endl;
std::cout << "Just to make sure we can call f(int): ";
f(777);
std::cout << std::endl;
auto b2{has_f<int>::value};
std::cout << "test(int) gives: " << b2 << std::endl;
}
Der Ausgang:
test(char*) gives: 0
Just to make sure we can call f(int): 777
test(int) gives: 0
Bah, 'is_detected' ist in Bibliothek Fundamentals v2 und nicht alle der Bibliothek Fundamentals ** v1 ** in C++ 17. :( – Yakk