Una variante della risposta di Bryan Chen che sembra più brutta, ma rende più facile per estendere a più controlli, e non richiede duplicare il codice che è condivisa tra D<type-with-f>
e D<type-without-f>
, è quello di utilizzare una catena ereditaria, in cui ogni fase controlla un membro aggiuntivo. L'unica duplicazione richiesta è l'ereditarietà dei costruttori, se appropriato.
struct A {
void f() { }
void g() { }
void i() { }
};
// The generic case. D<T, char[N]> simply provides what D<T, char[N+1]> provides.
template <typename T, typename U = char[1]>
struct D : D<T, char[sizeof(U) + 1]> {
using D<T, char[sizeof(U) + 1]>::D;
};
// The end of the chain. This is where T gets inherited. It declares all of its own
// specialisations as its friends, so that they can access other members of T.
template <typename T>
struct D<T, char[6]> : private T {
template <typename, typename>
friend struct D;
D(int) { }
void fun() { }
};
// Check for T::f.
template <typename T>
struct D<T, char[2 + !sizeof(&T::f)]> : D<T, char[3]> {
using D<T, char[3]>::D;
using T::f;
};
// Check for T::g.
template <typename T>
struct D<T, char[3 + !sizeof(&T::g)]> : D<T, char[4]> {
using D<T, char[4]>::D;
using T::g;
};
// Check for T::h.
template <typename T>
struct D<T, char[4 + !sizeof(&T::h)]> : D<T, char[5]> {
using D<T, char[5]>::D;
using T::h;
};
// Check for T::i.
template <typename T>
struct D<T, char[5 + !sizeof(&T::i)]> : D<T, char[6]> {
using D<T, char[6]>::D;
using T::i;
};
int main() {
D<A> d = 4; // ok: verify that constructors got inherited
// A &a = d; // error: verify that inheritance of A is private
d.f(); // ok: verify that f got inherited
d.g(); // ok: verify that g got inherited
// d.h(); // error: verify that h is not available
d.i(); // ok: verify that i got inherited
d.fun(); // ok: verify that the inheritance chain didn't get broken
}
Nota: invece di controllare &T::f
, si consiglia di fare qualcosa con std::declval<T>().f()
invece. Il primo non può gestire funzioni sovraccariche.
possibile duplicato di [È possibile scrivere un modello C++ per verificare l'esistenza di una funzione?] (Http://stackoverflow.com/questions/257288/is-it-possible-to-write-ac-template- to-check-for-a-functions-exist) – Klaus
@Klaus No, questo NON è un duplicato. Questa domanda può facilmente assumere che abbiamo già il carattere 'has_function_named_g'. Ora cosa? Come si applica alla dichiarazione 'using'? –
Angew