首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >类模板,在定义中引用它自己的类型

类模板,在定义中引用它自己的类型
EN

Stack Overflow用户
提问于 2018-06-26 08:18:21
回答 1查看 208关注 0票数 4

我想知道关于标准的以下情况,visual studio 2017和GCC中的哪一个是正确的。问题是,在类模板second中,visual studio中的标识符“second”总是引用具体类型,但在gcc中,它似乎是上下文相关的。

GCC的例子

代码语言:javascript
复制
template <typename...>
struct type_list{};

template<template <typename...> typename tmpl> 
struct tmpl_c
{
    template <typename...Ts> using type = tmpl<Ts...>;
};

template<typename> struct template_of;
template <template <typename...> typename tmpl, typename... Ts>
struct template_of<tmpl<Ts...>>{
    using type = tmpl_c<tmpl>; 

};


template <typename T>
struct first{};


template <typename T>
struct second
{
    // 'second' here refers to second<int>
    using test = second; 

    // 'second' here refers to the template second
    // is this due to the context? ie that the tmpl_c is expecting a template not a concrete type?
    using types = type_list<tmpl_c<first>, tmpl_c<second> >; 


    // second here refers to the concrete type 'second<int>'
    // this workaround is needed for visual studio as it seems second always 
    // refers to the concrete type, not the template.
    using types2 = type_list<tmpl_c<first>, typename template_of<second>::type >; 
};

Demo

和Visual Studio示例(只是不同的部分)

代码语言:javascript
复制
template <typename T>
struct second
{
    // 'second' here refers to second<int>
    using test = second; 

    // 'second' here refers to second<int>
    // this doesn't compile in visual studio as second<int> not the template.
    //using types = type_list<tmpl_c<first>, tmpl_c<second> >; 


    // second here refers to the concrete type 'second<int>'
    // this workaround is needed for visual studio as it seems second always 
    // refers to the concrete type, not the template.
    using types2 = type_list<tmpl_c<first>, typename template_of<second>::type >; 
};

Demo

由于template_of解决方法似乎在两者中都能正常工作,因此这是我目前唯一的选择。但我仍然想知道哪一个是正确的,或者是否有其他解决方法。

fixed in visual studio 15.8 Preview 2

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-26 08:53:42

Gcc是对的。根据injected-class-name for class template的使用规则,注入的类名既可以作为模板名,也可以作为类型名。

(强调我的)

与其他类一样,类模板也有一个

- class -name。injected-class-name可以用作模板名或类型名。

在以下情况下,注入的类名被视为类模板本身的模板名:

后接<

  • it的parameter

  • it用作与模板模板相对应的模板参数parameter

  • it是友元类模板declaration.

的精心设计的类说明符中的最终标识符

否则,它将被视为类型名,等同于<>中封装的类模板的模板参数后跟模板名。

也就是说,

代码语言:javascript
复制
template <typename T>
struct second
{
    
    // second is same as second<T>
    using test = second; 

    // second is considered as a template-name
    // it's used as template argument for a template template parameter
    using types = type_list<tmpl_c<first>, tmpl_c<second> >; 

    // second is same as second<T>
    using types2 = type_list<tmpl_c<first>, typename template_of<second>::type >; 
};
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51033338

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档