我从rhalbersma得到了这段代码,但它不能在VC 2010中编译。我不知道我在做什么错。此模板代码不会编译。有任何想法吗?
template<typename Derived>
struct enable_crtp
{
private:
// typedefs
typedef enable_crtp Base;
public:
// casting "down" the inheritance hierarchy
Derived const* self() const
{
return static_cast<Derived const*>(this);
}
// write the non-const version in terms of the const version
// Effective C++ 3rd ed., Item 3 (p. 24-25)
Derived* self()
{
return const_cast<Derived*>(static_cast<Base const*>(this)->self());
}
protected:
// disable deletion of Derived* through Base*
// enable deletion of Base* through Derived*
~enable_crtp()
{
// no-op
}
};
template<typename FX>
class FooInterface
:
private enable_crtp<FX>
{
public:
// interface
void foo() { self()->do_foo(); }
};
class FooImpl
:
public FooInterface<FooImpl>
{
private:
// implementation
friend class FooInterface<FooImpl> ;
void do_foo() { std::cout << "Foo\n"; }
};
class AnotherFooImpl
:
public FooInterface<AnotherFooImpl>
{
private:
// implementation
friend class FooInterface<AnotherFooImpl>;
void do_foo() { std::cout << "AnotherFoo\n"; }
};
template<template<typename> class F, int X>
class BarInterface
:
private enable_crtp< F<X> >
{
// interface
void bar() { self()->do_bar(); }
};
template< int X >
class BarImpl
:
public BarInterface< BarImpl, X >
{
private:
// implementation
friend class BarInterface< ::BarImpl, X >;
void do_bar() { std::cout << X << "\n"; }
};
int main()
{
FooImpl f1;
AnotherFooImpl f2;
BarImpl<1> b1;
BarImpl<2> b2;
f1.foo();
f2.foo();
b1.bar();
b2.bar();
return 0;
}
什么是编译错误? – jrad 2012-07-20 01:10:03
无法编译,有时是由环境设置引起的。也许在VS2010中缺少第三方库。 – 2012-07-20 01:17:30
如果您缩小用例范围,您有多个问题并且更可能获得帮助。删除Foo或Bar,然后集中解决一个问题。包含从编译器获得的错误消息,以便那些不能立即访问的错误消息也可以提供帮助。 – 2012-07-20 01:59:33