[C++] C++11 decltype关键字

在C++11中,decltype和auto都是关于类型的关键字。auto能够在编译时自动选择变量类型(当然还有其他很多用法,这里主要记录decltype),而decltype则能够推测出变量的类型,这与typeid关键字有点相似,但两者的机制完全不同。

typeid

typeid使用的是RTTI(Run-Time Type Identification)机制,由于它是在运行时进行类型确认,会影响运行效率。

decltype

decltype关键字则是在编译时便确定变量类型,它有许多有用的用法,例如使用已有变量定义新变量的类型、重用匿名类型、泛型编程中结合auto追踪函数的返回值类型(例子如下)。

template <typename _Tx, typename _Ty>
auto multiply(_Tx x, _Ty y)->decltype(_Tx*_Ty)
{
    return x*y;
}

详细参考原博客

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.