我采取了Nicola Bonelli和Johannes Schaub非常有帮助的答案,并将他们合并成一个解决方案,即恕我直言,更具可读性,清晰,不需要typeof扩展:
template <class Type>
class TypeHasToString
{
// This type won't compile if the second template parameter isn't of type T,
// so I can put a function pointer type in the first parameter and the function
// itself in the second thus checking that the function has a specific signature.
template <typename T, T> struct TypeCheck;
typedef char Yes;
typedef long No;
// A helper struct to hold the declaration of the function pointer.
// Change it if the function signature changes.
template <typename T> struct ToString
{
typedef void (T::*fptr)();
};
template <typename T> static Yes HasToString(TypeCheck< typename ToString<T>::fptr, &T::toString >*);
template <typename T> static No HasToString(...);
public:
static bool const value = (sizeof(HasToString<Type>(0)) == sizeof(Yes));
};
我用gcc 4.1.2查了一下。信贷主要是尼古拉Bonelli和约翰Schaub,所以给他们一个投票,如果我的回答可以帮助你:)... 展开详请