【问题标题】:class template, referring to its own type in definition类模板,在定义中引用它自己的类型
【发布时间】:2018-06-26 00:18:21
【问题描述】:

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

GCC 示例

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 示例(只是不同的位)

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

【问题讨论】:

  • 众所周知,MSVC 远不符合标准。

标签: c++ templates language-lawyer metaprogramming


【解决方案1】:

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

(强调我的)

与其他类一样,类模板具有注入类名称。注入的类名可以用作模板名或类型名。

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

  • 后面是
  • 用作模板参数,对应一个模板模板参数
  • 它是友元类模板声明的详细类说明符中的最终标识符。

否则,它被视为类型名,相当于模板名后跟中包含的类模板的模板参数。

也就是说,

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 >; 
};

【讨论】:

    猜你喜欢
    • 2021-08-31
    • 1970-01-01
    • 2023-01-03
    • 1970-01-01
    • 1970-01-01
    • 2010-09-20
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    相关资源
    最近更新 更多