【问题标题】:Flexibility of template alias in C++0xC++0x 中模板别名的灵活性
【发布时间】:2010-11-11 09:34:11
【问题描述】:

据我了解,C++0x 中的模板别名将允许我们执行以下操作:

template <typename T>
using Dictionary = std::map< std::string, T >;

Dictionary<int> ints;
ints[ "one" ] = 1;
ints[ "two" ] = 2;

我有两个问题:

首先,我们能否做到这一点(绑定到任何类型,或者只是模板):

template <typename Iter>
using ValueType = std::iterator_traits<Iter>::value_type;

其次,使用别名需要在模板中使用typename关键字,例如:

template <typename Iter>
typename ValueType<Iter> sum(Iter first, Iter last) { ... }
// ^ required?

或者在别名声明中是否需要?

using ValueType = typename std::iterator_traits<Iter>::value_type;
//                   ^ required?

或者两者都没有?

【问题讨论】:

    标签: c++ templates c++11 typename


    【解决方案1】:

    语法是:

    template <typename Iter>
    using ValueType = typename std::iterator_traits<Iter>::value_type;
    

    和你的第二个一样。

    来源: http://www2.research.att.com/~bs/C++0xFAQ.html#template-alias

    他们的例子是:

    template<int N>
        using int_exact = typename int_exact_traits<N>::type;  // define alias for convenient notation
    

    【讨论】:

      【解决方案2】:

      当成员类型跟在:: 运算符之后并且模板ID 在它之前时,需要typename

      您提到的typename 的用法并不特定于模板别名,也不是必需的,除非您为::type 之类的成员设置别名,但这是一个常见的用例。

      例如,在将简单别名引入现有模板时,没有typename

      template< typename x >
      class bar;
      
      template< typename x >
      using foo = bar< x >; // no typename needed
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-06
        • 1970-01-01
        • 2011-01-08
        相关资源
        最近更新 更多