灵活的C++模板别名0X
问题描述:
据我了解,在C++ 0x中模板的别名将使我们能够做到以下几点:灵活的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?
或者都不是?
答
的语法是:
template <typename Iter>
using ValueType = typename std::iterator_traits<Iter>::value_type;
与你的第二个。
来源: http://www2.research.att.com/~bs/C++0xFAQ.html#template-alias
他们的例子是:当一个部件类型遵循::
操作者模板id它前面
template<int N>
using int_exact = typename int_exact_traits<N>::type; // define alias for convenient notation
答
typename
是必需的,。
您提到的typename
的用法不是特定于模板别名,也不是必需的,除非您将某个成员设为别名,例如::type
,但这是一种常见用例。
例如,在向现有模板引入简单别名时没有typename
。
template< typename x >
class bar;
template< typename x >
using foo = bar<x>; // no typename needed