1
#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;
}

我越来越:

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

我怀疑这是因为 S 的定义将自己用作基类。(正确的?)

解决此问题的最佳方法是什么?

更新:

这是固定版本:

#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;
}
4

2 回答 2

2

定义C而不是仅仅声明它。

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

在您使用它的地方,部分特化不匹配并且主模板被实例化,这只是一个声明。

您可能想知道为什么不考虑特化:特化不考虑转换,而只考虑静态类型。这就是为什么它们与继承如此背道而驰的原因。

于 2012-10-27T18:46:09.330 回答
0

你可以只委托S::f而不是使用继承吗?

template<int n> struct S {
    constexpr A f() { return C<S<n/2>, S<n-n/2>>::f(); }
};
于 2012-10-27T18:54:18.797 回答