c++ - using用法 - typedef別名
在C++ 11中'typedef'和'using'有什麼區別? (3)
我知道在C ++ 11中,我們現在可以using
用於寫入類型別名,如typedef
s:
typedef int MyInt;
據我所知,相當於:
using MyInt = int;
這種新的語法來源於努力去表達“ template typedef
”:
template< class T > using MyType = AnotherType< T, MyAllocatorType >;
但是,對於前兩個非模板示例,標準中是否還有其他細微差別? 例如, typedef
以“弱”方式進行別名。 也就是說,它不會創建新的類型,而只是一個新的名稱(這些名稱之間的轉換是隱含的)。
它是否與using
相同或是否會生成新類型? 有什麼區別嗎?
使用語法在模板中使用時具有優勢。 如果您需要類型抽象,但還需要保留模板參數以便將來可以指定。 你應該寫這樣的東西。
template <typename T> struct whatever {};
template <typename T> struct rebind
{
typedef whatever<T> type; // to make it possible to substitue the whatever in future.
};
rebind<int>::type variable;
template <typename U> struct bar { typename rebind<U>::type _var_member; }
但是使用語法簡化了這個用例。
template <typename T> using my_type = whatever<T>;
my_type<int> variable;
template <typename U> struct baz { my_type<U> _var_member; }
它們基本上是相同的,但using
提供alias templates
非常有用。 我能找到一個很好的例子如下:
namespace std {
template<typename T> using add_const_t = typename add_const<T>::type;
}
所以,我們可以使用std::add_const_t<T>
來代替typename std::add_const<T>::type
除此之外,它們在很大程度上是相同的
The alias declaration is compatible with templates, whereas the C style typedef is not.