aliased templates in nested classes
I am trying to get a template alias for T2<B>
starting from an instance of C.
template<typename A>
struct T1
{
template<typename B>
struct T2{};
};
template<typename A>
class C
{
T1<A> t;
};
template<typename A>
using U1=decltype(C<A>::t);
template<typename A, typename B>
using U2=typename U1<A>::T2<B>;
I get a compiler failure with gcc 4.8:
gg.cc:18:28: error: expected ‘;’ before ‘<’ token
using U2=typename U1<A>::T2<B>;
I have used the typename keyword in every sensible location, but can't get the U2 definition to compile.
What is the correct syntax here? It would be even better if I could get a definition of U2 without resorting to U1.
You need to use the template
disambiguator to tell the compiler to parse T2
as the name of a template (and the subsequent <
and >
as delimiters of the corresponding template arguments):
template<typename A, typename B>
using U2=typename U1<A>::template T2<B>;
// ^^^^^^^^
Here is a compiling live example.
Here you can find some more information on when you should use the template
disambiguator (and the typename
disambiguator as well, although you seem to be aware of that one).
When the compiler compiles the following:
template<typename A, typename B>
using U2=typename U1<A>::T2<B>;
After it reads the nested name specifier U1<A>::
, it doesn't know which specialization of U1
it is in, because A
is unknown. Each U1
specializaiton could be totally different, and depend on what A
is. So it has no idea what kind of name T1
is. In particular it doesn't know whether it is a template name or not. (For example U1<int>::T1
could be totally different to what U1<char>::T1
is.)
For this reason you need to explicitly tell the compiler that T1
is going to be a template name by using the template
keyword before T1
.
上一篇: 推断CRTP中的模板成员函数的返回类型
下一篇: 嵌套类中的别名模板