Albert Albert - 2 months ago 15
C++ Question

c++ static polymorphism / CRTP with additional template parameters accessing base class member

I would like to implement static polymorphism using CRTP and also add additional types to the templates parameters.

Providing the following scenario, how can I directly access Base members from a Derived class? Is it possible without specifying the full type of the Base class?

#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 output:

error: use of undeclared identifier '_a'

Answer

You can add a using declaration in your class:

template<class X>
struct Derived: public Base<Derived<X>, X> {

  using Base<Derived<X>, X>::_a;

  /* ... */

};

You still have to specify it once though.

Comments