好的,假设我想检查模板参数是否有嵌套类型/typedef XYZ。
template <class T>
struct hasXZY
{
typedef char no;
typedef struct { char x[2]; } yes;
template <class U>
static yes f(typename U::XYZ*);
template <class /*U*/>
static no f(...);
enum {value = sizeof(f<T>(0))==sizeof(yes)};
};
工作正常,正如预期的那样。
现在考虑一下:
template <class T>
struct hasXZY
{
typedef char no;
typedef struct { char x[2]; } yes;
static yes f(typename T::XYZ*);
static no f(...);
enum {value = sizeof(f(0))==sizeof(yes)};
};
hasXYZ<int>
现在导致编译时错误。好的, f 不是模板函数。但另一方面,当hasXYZ
为 int via 实例化时,编译器可以很容易地从候选列表中hasXYZ<int>::value
排除。f(int::XYZ*)
我只是不明白为什么类模板中成员函数声明的实例化失败一定会导致整个类实例化失败。有任何想法吗?
编辑:我的问题是:为什么成员函数声明都是格式正确的?由于编译器仅在使用方法时才实例化方法,为什么需要正确声明。将上述示例 2 视为此功能的可能用例。