각 단계에서 하나의 추가 구성원을 확인하는 상속 체인입니다. 필요한 경우에만 생성자의 상속이 필요합니다.
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
}
참고 : 대신 &T::f
을 확인, 당신은 대신 std::declval<T>().f()
으로 뭔가를 할 수 있습니다. 전자는 오버로드 된 함수를 처리 할 수 없습니다.
출처
2015-01-30 12:15:57
hvd
가능한 복제본 [함수의 존재를 확인하기 위해 C++ 템플릿을 작성할 수 있습니까?] (http://stackoverflow.com/questions/257288/is-it-possible-to-write-ac-template- 기능 확인 - 존재 여부) – Klaus
@Klaus 아니요, 이것은 중복이 아닙니다. 이 질문은 쉽게 우리가 이미 has_function_named_g '이라는 특성을 가지고 있다고 가정 할 수 있습니다. 이제 뭐? 'using' 선언에 어떻게 적용합니까? –
Angew