Modern cpp tutorial

[[C++]]

https://github.com/changkun/modern-cpp-tutorial

https://changkun.de/modern-cpp/

if (std::is_same<decltype(x), int>::value)  
    std::cout << "type x == int" << std::endl;  
if (std::is_same<decltype(x), float>::value)  
    std::cout << "type x == float" << std::endl;  
if (std::is_same<decltype(x), decltype(z)>::value)  
    std::cout << "type z == type x" << std::endl;  

其中,std::is_same<T, U> 用于判断 T 和 U 这两个类型是否相等。输出结果为:

type x == int  
type z == type x

我们使用了 decltype 和 std::is_same 这两个属于现代 C++ 的语法,简单来说,decltype 用于类型推导,而 std::is_same 用于比较两个类型是否相同.

decltype 关键字是为了解决 auto 关键字只能对变量进行类型推导的缺陷而出现的。它的用法和 typeof 很相似:

decltype(表达式)  

有时候,我们可能需要计算某个表达式的类型,例如:

auto x = 1;  
auto y = 2;  
decltype(x+y) z;

注意:typename 和 class 在模板参数列表中没有区别,在 typename 这个关键字出现之前,都是使用 class 来定义模板参数的。但在模板中定义有嵌套依赖类型的变量时,需要用 typename 消除歧义