简体   繁体   English

嵌套类中的别名模板

[英]aliased templates in nested classes

I am trying to get a template alias for T2<B> starting from an instance of C. 我正在尝试从C的实例开始获取T2<B>的模板别名。

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: 我在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. 我在每个明智的位置都使用typename关键字,但是无法编译U2定义。

What is the correct syntax here? 正确的语法是什么? It would be even better if I could get a definition of U2 without resorting to U1. 如果我不求助于U1而得到U2的定义,那就更好了。

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消歧器来告诉编译器将T2解析为模板的名称(以及随后的<>作为相应模板参数的定界符):

    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). 在这里,您可以找到有关何时应该使用template消歧器(以及typename消歧器)的更多信息,尽管您似乎已经意识到了这一点。

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. 在读取嵌套名称说明符U1<A>::之后,由于A是未知的,所以它不知道它在U1哪个专业领域中。 Each U1 specializaiton could be totally different, and depend on what A is. 每个U1专业化可能完全不同,并且取决于A是什么。 So it has no idea what kind of name T1 is. 因此,不知道T1是什么样的名称。 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.) (例如, U1<int>::T1可能与U1<char>::T1完全不同。)

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 . 因此,您需要通过在T1之前使用template关键字来明确告知编译器T1将是模板名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM