我想使用CRTP实现静态多态性,并向模板参数添加其他类型。
提供以下场景,如何直接从 Derived 类访问 Base 成员?是否可以不指定 Base 类的完整类型?
#include <iostream>
template<class Derived, class X>
struct Base
{
void set_a( int a ) { _a = a; }
protected:
int _a;
};
template<class X>
struct Derived: public Base<Derived<X>, X>
{
int get_a( )
{
// return Base<Derived<X>,X>::_a; // This works!
return _a; // error: use of undeclared identifier '_a'
}
};
struct foo;
int main()
{
Derived<foo> test;
auto base_p = static_cast< Base<Derived<foo>, foo>* >( &test );
base_p->set_a( 42 );
int a = test.get_a();
std::cout << a << std::endl;
}
g++5.3.1 / clang++3.8.0 输出:
error: use of undeclared identifier '_a'