【发布时间】:2013-08-22 13:41:02
【问题描述】:
我正在尝试使用一种简单形式的 CRTP(Curiously Recurring Template Pattern),因为我有几个类,每个类都有几个相关的类,我想要一种将它们绑定在一起的方法(例如,我有类例如 Widget、Doobry 和 Whatsit,以及相关的类 WidgetHandle、DoobryHandle 和 WhatsitHandle)。
我用来从Base 继承的每个类都添加了一个value_type 类型定义,以便基类可以将其称为typename TWrapper::value_type。
struct WidgetHandle {};
template <typename TWrapper>
class Base
{
public:
Base(typename TWrapper::value_type value_)
: value(value_) {}
typename TWrapper::value_type value;
};
class Widget : public Base<Widget>
{
public:
typedef WidgetHandle value_type;
Widget(WidgetHandle value_) : Base<Widget>(value_) {}
};
int main(int argc, char* argv[])
{
Widget i(WidgetHandle());
return 0;
}
但是,我遇到了编译错误:
scratch1.cpp(10): error C2039: 'value_type' : is not a member of 'Widget'
scratch1.cpp(16) : see declaration of 'Widget'
scratch1.cpp : see reference to class template instantiation 'Base<TWrapper>' being compiled
1> with
1> [
1> TWrapper=Widget
1> ]
scratch1.cpp(10): error C2039: 'value_type' : is not a member of 'Widget'
这是 VS2010 的问题,尽管我在 clang 中遇到了类似的错误。我在这里错过了什么?
【问题讨论】:
-
当您将
Widget作为参数传递给Base时,它是不完整的类型。 -
事实上,我在任何地方都没有看到
value_type的定义。 -
@PetrBudnik 在
Widgetbody 的开头。 -
@jrok 我已经纠正了。
-
Here 是另一种可能的解决方法。