我从 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;
}