template<typename T> struct A {
auto func() -> decltype(T::func()) {
return T::func();
}
};
class B : public A<B> {
void func() {
}
};
对我来说似乎很简单。但是 MSVC 无法编译。
visual studio 2010\projects\temp\temp\main.cpp(4): error C2039: 'func' : is not a member of 'B'
visual studio 2010\projects\temp\temp\main.cpp(8) : see declaration of 'B'
visual studio 2010\projects\temp\temp\main.cpp(8) : see reference to class template instantiation 'A<T>' being compiled
with
[
T=B
]
visual studio 2010\projects\temp\temp\main.cpp(4): error C3861: 'func': identifier not found
即使编译器会很乐意接受调用该函数。下面的示例可以正常编译。
template<typename T> struct A {
void func() {
return T::func();
}
};
class B : public A<B> {
void func() {
}
};
我在尝试使用模板参数中的任何类型时遇到了同样的问题。
template<typename T> struct A {
typedef typename T::something something;
};
class B : public A<B> {
typedef char something;
};
visual studio 2010\projects\temp\temp\main.cpp(4): error C2039: 'something' : is not a member of 'B'
而 B 类明确定义了一种称为“某物”的类型。编译器非常乐意在 T、T& 或 T* 类型的对象上调用函数,但我似乎无法从 T 访问任何类型。
最佳答案
您正在尝试在声明之前使用 T::func
。这就是编译器对你大喊大叫的原因。请注意,当您从类派生时,如果该类来自类模板,则会生成该类。类的隐式生成(称为隐式实例化)需要为其所有成员生成声明(因此编译器知道类的 sizeof 值,并可以对其执行查找)。
因此它还实例化声明 auto func() -> decltype(T::func())
并且肯定会在这里失败。
关于c++ - CRTP 失败 w/decltype,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4225706/