模板成员类的模板别名

Template alias for template member class

本文关键字:别名 成员类      更新时间:2023-10-16

我有以下模板

template<class F>
struct A{
  template<int N>
  struct B{
    using type = int;
  };
};

不过,我想制作一个模板别名:

//doesn't compile.
template<class F, int N >
using alias_A = typename A<F>::B<N>::type;
GCC:
question.cpp:12:36: error: expected ';' before '::' token
 using alias_A = typename A<F>::B<N>::type;
                                    ^
question.cpp:12:36: error: 'type' in namespace '::' does not name a type

调试时我发现:

//does compile
struct C{};
using alias_B = typename A<C>::B<0>::type;

有人能指出我做错了什么吗?我觉得我错过了一些显而易见的东西。

您需要告诉C++它的内部类型B<N>是一个模板:

template<class F, int N >
using alias_A = typename A<F>::template B<N>::type;

在这种情况下,编译器将您编写的内容解析为operator<,而不是模板参数的大括号。

这篇文章详尽地介绍了你何时以及为什么需要这样做。