【发布时间】:2010-11-19 14:03:01
【问题描述】:
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 访问任何类型。
【问题讨论】:
-
编译器不会愉快地实例化 A::func,我们在您的 previous question 中介绍了这一点。
-
你可以认为这是一个竞态条件:A 的实例化取决于 B 的定义,因为 A::func 的返回类型取决于 B::func 的返回类型,然而定义 B(并因此声明 B::func)依赖于 A 作为基类。
-
@Fred:关于我的 CRTP 失败,你说得对。但是,如果您想让答案被接受,您必须将其作为一个发布,而不是评论。
-
我认为这不值得回答,需要用 0x 仔细检查。
标签: c++ visual-c++ c++11 crtp decltype