【发布时间】:2011-08-25 18:48:59
【问题描述】:
我阅读了Wikipedia article 关于在 C++ 中奇怪地重复出现的模板模式,用于执行静态(阅读:编译时)多态性。我想对其进行概括,以便可以根据派生类型更改函数的返回类型。 (这似乎应该是可能的,因为基类型知道模板参数的派生类型)。不幸的是,以下代码无法使用 MSVC 2010 编译(我现在无法轻松访问 gcc,所以我还没有尝试过)。有人知道为什么吗?
template <typename derived_t>
class base {
public:
typedef typename derived_t::value_type value_type;
value_type foo() {
return static_cast<derived_t*>(this)->foo();
}
};
template <typename T>
class derived : public base<derived<T> > {
public:
typedef T value_type;
value_type foo() {
return T(); //return some T object (assumes T is default constructable)
}
};
int main() {
derived<int> a;
}
顺便说一句,我有一个使用额外模板参数的解决方法,但我不喜欢它——当将许多类型传递到继承链上时它会变得非常冗长。
template <typename derived_t, typename value_type>
class base { ... };
template <typename T>
class derived : public base<derived<T>,T> { ... };
编辑:
MSVC 2010 在这种情况下给出的错误消息是error C2039: 'value_type' : is not a member of 'derived<T>'
g++ 4.1.2(通过codepad.org)说error: no type named 'value_type' in 'class derived<int>'
【问题讨论】:
-
请注意,codepad.org 可以为您编译和运行代码,我相信它使用 gcc/g++。所以你永远不会脱离 g++ :)
-
您能补充一下您遇到的错误,以便我对读者有用。
-
@Seth:Ideone 肯定使用 gcc,所以它是另一个 :)
-
@Seth:感谢关于 codepad.org 的提示! @Sriram:好电话。我添加了它们。
标签: c++ templates inheritance typedef crtp