谁能解释为什么下面的代码不能编译:
template <typename P>
struct Base
{
friend typename P::One;
friend typename P::Two;
friend typename P::Three;
};
template<typename U, typename D, typename T>
struct Derived : public Base<Derived<U,D,T>>
{
using One = U;
using Two = D;
using Three = T;
};
错误是:
..\PRP\main.cpp:3:1: error: no type named 'One' in 'struct Derived<A, B, C>'
{
^
..\PRP\main.cpp:3:1: error: no type named 'Two' in 'struct Derived<A, B, C>'
..\PRP\main.cpp:3:1: error: no type named 'Three' in 'struct Derived<A, B, C>'
为什么下面的代码可以完美编译:
template <typename T>
struct Sum
{
constexpr static int sze = T::uno + T::due + T::tre;
};
template<int i, int j, int k>
struct Triple : public Sum<Triple<i, j, k>>
{
constexpr static int uno = i;
constexpr static int due = j;
constexpr static int tre = k;
};
两者有什么区别?我认为这与模板扣除顺序有关,但我可能错了。
我在带有 C++11 标志的 Win7 上使用 MinGW 4.8。 谢谢!
最佳答案
您的代码中没有发生模板参数推导,因此这与推导无关。
问题是由于尝试使用 Derived
的成员引起的而它是一个不完整的类型。
友元声明在 Base<Derived<U,D,T>>
的实例化期间由编译器立即处理它出现在 Derived
的基类列表中,然后 Derived
不完整,因此无法尝试使用其成员。
Sum
中的静态成员不会自动实例化,并且在 Triple
的声明中不需要.如果稍后使用静态成员,则 Triple
是一个完整的类型,其成员可以被引用。
如果您尝试使用 Sum<T>::sze
在 Sum
的定义中你会得到一个类似的错误,因为T
在这一点上还不是一个完整的类型:
template <typename T>
struct Sum
{
constexpr static int sze = T::uno + T::due + T::tre;
char buf[sze];
};
template<int i, int j, int k>
struct Triple : public Sum<Triple<i, j, k>>
{
constexpr static int uno = i;
constexpr static int due = j;
constexpr static int tre = k;
};
Triple<1, 2, 3> t;
关于c++ - 模板参数推导顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28562596/