2021-01-29 decltype类型推断(c++17)

decltype返回一个实例的声明类型,或者是一个表达式的返回值类型。

语法:

decltype(entity)

decltype(expression)

如果参数是未括号化的id表达式或未括号化的类成员访问表达式,则decltype会产生此表达式命名的实体的类型。 如果没有这样的实体,或者参数指定了一组重载函数,则程序格式错误。

代码用例如下:

#include<iostream>
#include<type_traits>
using namespace std;

struct A {double x;};
const A* a;

template<typename T, typename U>
auto add(T t, U u) -> decltype(t + u){
    return t + u;
}

int main()
{
    int i = 22;
    decltype(i) j = i*2;
    cout<<"type(i) == type(j) ?" << boolalpha << is_same_v<decltype(i), decltype(j)> <<'\n';
    cout<< "i=" <<i <<", " << "j="<<j<<endl;

    auto f = [](int a, int b) -> int{
        return a * b;
    };
    decltype(f) g = f; 
    i = f(2, 2);
    j = f(3, 3);
    cout<< "i=" <<i <<", " << "j="<<j<<endl;
    return 0;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值