我從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