Andrew Tomazos
Andrew Tomazos

Reputation: 68618

C++11: Workaround Use Of This Incomplete Type Error?

#include <iostream>
#include <array>
using namespace std;

constexpr int N = 10;
constexpr int f(int x) { return x*2; }

typedef array<int, N> A;

template<int... i> struct F { constexpr A f() { return A{{ f(i)... }}; } };

template<class X, class Y> struct C;
template<int... i, int... j>
struct C<F<i...>, F<j...>> : F<i..., (sizeof...(i)+j)...> {};

template<int n> struct S : C<S<n/2>, S<n-n/2>> {}; // <--- HERE
template<> struct S<1> : F<0> {};

constexpr auto X = S<N>::f();

int main()
{
        cout << X[3] << endl;
}

I'm getting:

test.cpp:15:24: error: invalid use of incomplete type ‘struct C<S<5>, S<5> >’

I suspect this is because the definition of S is using itself as a base class. (Correct?)

What is the best way to fix this?

Update:

Here is the fixed version:

#include <iostream>
#include <array>
using namespace std;

constexpr int N = 10;
constexpr int f(int x) { return x*2; }

typedef array<int, N> A;

template<int... i> struct F { static constexpr A f() { return A{{ ::f(i)... }}; } };

template<class A, class B> struct C {};
template<int... i, int... j> struct C<F<i...>, F<j...>> : F<i..., (sizeof...(i)+j)...>
{
        using T = F<i..., (sizeof...(i)+j)...>;
};

template<int n> struct S : C<typename S<n/2>::T, typename S<n-n/2>::T> {};
template<> struct S<1> : F<0> { using T = F<0>; };

constexpr auto X = S<N>::f();

int main()
{
        cout << X[3] << endl;
}

Upvotes: 1

Views: 297

Answers (2)

pmr
pmr

Reputation: 59811

Define C instead of just declaring it.

template<class X, class Y> struct C {};

In the place you use it the partial specialization does not match and the primary template is instantiated, which is just a declaration.

You may wonder why that specialization is not considered: specializations don't consider conversions, but just the static type. That's why they are so treacherously incompatible with inheritance.

Upvotes: 2

aschepler
aschepler

Reputation: 72271

Could you just delegate S::f instead of using inheritance?

template<int n> struct S {
    constexpr A f() { return C<S<n/2>, S<n-n/2>>::f(); }
};

Upvotes: 0

Related Questions