【问题标题】:Is it possible to define an alias for a template-template parameter?是否可以为模板模板参数定义别名?
【发布时间】:2012-12-15 21:44:48
【问题描述】:

为了好玩,我正在尝试使用模板模板。我有以下课程:

template<template<class> class T, typename R> class Unit
{    
    using FullType = T<R>;
    using Ratio = R;
    //using Type = T;

    ...
};

我已将类型RT&lt;R&gt; 定义为成员类型RatioFullType。 是否可以将T 别名为Type

上面的注释行在 g++ 4.7 上给了我以下错误:

expected nested-name-specifier before 'Type'
using-declaration for non-member at class scope
expected ';' before '=' token
expected unqualified-id before '=' token

我尝试了一些或多或少的随机语法,但都没有编译。

谢谢!

【问题讨论】:

    标签: c++ templates c++11 template-templates


    【解决方案1】:

    由于T 不是类型,所以提出的问题没有意义。但是,您可以为T 起一个别名,例如:

    template <template <typename> class T, typename R> class Unit
    {
        template <typename U> using MyTemplate = T<U>;
        // ...
    
        // use e.g. MyTemplate<int> to get T<int>
    };
    

    在 C++11 之前,您将需要更多符号方面的内容,如 in this answer of mine 所述(例如,标准分配器的 rebind 机制在标准库中使用。)

    【讨论】:

    • 谢谢,这正是我想要的。我会编辑问题以使其有意义
    【解决方案2】:

    您不能为T 创建别名。委员会讨论了以下内容以创建 T 的别名(因为很晚的 C++11 草案包含说明它 T 的别名,Defect Report清理干净)。

    // Courtesy of @KerrekSB
    template <template <typename> class T, typename R> class Unit
    {
        template <typename U> using MyTemplate = T<U>;
        // ...
    
        // use e.g. MyTemplate<int> to get T<int>
    };
    

    注意虽然MyTemplate&lt;int&gt;T&lt;int&gt; 的类型相同,但MyTemplateT 的类型相同。 http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1286 的措辞本应改变这一点,但在上次会议上,它被认为是一种非常特殊的机器,并不真正适合原来的别名模板(自己的模板),它被推回审查。为了达到这种效果,未来的using MyTemplate = T; 可能符合要求(当然,如果提议并被接受)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-28
      • 2019-02-06
      • 1970-01-01
      • 1970-01-01
      • 2015-05-15
      • 1970-01-01
      • 2016-11-18
      相关资源
      最近更新 更多