CRTP with base class trying to get the return type of a derived class member: invalid use of incomplete type

StackOverflow https://stackoverflow.com/questions/17690525

Question

Consider the following code (it's for example purpose only):

#include <iostream>
#include <type_traits>
#include <array>

template <
class Crtp, 
class Vector = typename std::decay<decltype(std::declval<Crtp>().data())>::type, 
class Scalar = typename std::decay<decltype(std::declval<Crtp>().data(0))>::type
>
struct Base
{;};

template <
class Vector = std::array<double, 3>, 
class Scalar = typename std::decay<decltype(std::declval<Vector>()[0])>::type
>
struct Derived
: public Base<Derived<Vector, Scalar>>
{
    Vector _data;
    inline Vector& data() {return _data;}
    inline const Vector& data() const {return _data;}
    inline Scalar& data(const unsigned int i) {return _data[i];}
    inline const Scalar& data(const unsigned int i) const {return _data[i];}
};

int main()
{
    Derived<> d;
    return 0;
}

It returns the following error:

main.cpp: In instantiation of 'struct Derived<>':
main.cpp:28:14: required from here
main.cpp:16:8: error: invalid use of incomplete type 'struct Derived<>'
main.cpp:16:8: error: declaration of 'struct Derived<>'

Is there a way to solve this (without using typedefs and only using templates)?

Was it helpful?

Solution

This is pretty messy, since Derived isn't complete when template argument deduction happens for Base. I assume the obvious answer - pass Vector and Scalar explicitly - is unsatisfactory. How about:

template <template <class, class> class Derived,
          class Vector, class Scalar>
struct Base {};

template <class Vector, class Scalar>
struct Derived : Base<Derived, Vector, Scalar> {};

Why the strange restriction to not use typedef? I find:

template <class Vector>
using ScalarTypeOf =
  typename std::decay<decltype(std::declval<Vector>()[0])>::type;

template <class Crtp>
using VectorTypeOf =
  typename std::decay<decltype(std::declval<Crtp>().data())>::type;

template <class Crtp>
struct Base {
  using Vector = VectorTypeOf<Crtp>;
  using Scalar = ScalarTypeOf<Vector>;
};

template <class Vector>
struct Derived : public Base<Derived<Vector>> {
  using Scalar = ScalarTypeOf<Vector>;
};

to be a bit more readable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top