Given a base class using CRTP, I am considering a member declaration in a base template where the type depends on the derived class.
While the following works as intended:
template <class T> class BaseTraits;
template <class T> class Base {
using TypeId = typename BaseTraits<T>::TypeId;
TypeId id;
public:
Base() { id = 123; }
TypeId getId() { return id; }
};
class Derived;
template <> class BaseTraits<Derived> {
public:
using TypeId = int;
};
class Derived : public Base<Derived> {};
int main(int argc, char ** argv) {
Derived foo;
return foo.getId();
}
I wonder if I can simplify the implementation. I could add a second template to the template Baseand make BaseTraitsit easier or even get rid of it. However, the above snippet is already an attempt to remove the second template parameter. I am considering solutions that do not include a second template parameter for Base.
I tried something like the following, but it does not compile:
error: invalid use of incomplete type 'class Derived'
template <class T> class Base {
using TypeId = typename T::TypeId;
TypeId id;
public:
Base() { id = 123; }
TypeId getId() { return id; }
};
class Derived : public Base<Derived> {
public:
using TypeId = int;
};
int main(int argc, char ** argv) {
Derived foo;
return foo.getId();
}
UPDATE:
- I am limited to C ++ 14.
Base must be a template.- .