C++20中的简写函数模板(abbreviated function template)

      简写函数模板(abbreviated function template):当占位符类型(auto或concept auto)出现在函数声明或函数模板声明的参数列表中时,该声明将声明一个函数模板,并且每个占位符的一个虚构模板参数(one invented template parameter)将附加到模板参数列表。如下所示:简写函数模板只是指定函数模板的一种简便方法

void f1(auto); // same as template<class T> void f1(T)
void f2(C1 auto); // same as template<C1 T> void f2(T), if C1 is a concept
void f3(C2 auto...); // same as template<C2... Ts> void f3(Ts...), if C2 is a concept
void f4(const C3 auto*, C4 auto&); // same as template<C3 T, C4 U> void f4(const T*, U&);

template<class T, C U>
void g(T x, U y, C auto z); // same as template<class T, C U, C W> void g(T x, U y, W z);

template<>
void f4<int>(const int*, const double&); // specialization of f4<int, const double>

      以下为测试代码:

namespace {

//template<typename T>
//T get_sum(T a, T b)
auto get_sum(auto a, auto b) // 不受约束的auto
{
    return (a + b);
}

template <typename T>
concept C = std::is_integral_v<T> || std::is_floating_point_v<T>;

auto get_sum2(C auto a, C auto b) // 受约束的auto
{
    return (a + b);
}

} // namespace

int test_abbreviated_function_template()
{
    std::cout << "sum: " << get_sum(6, 8) << std::endl;
    std::cout << "sum: " << get_sum(6, 8.8) << std::endl;
    std::cout << "sum: " << get_sum(std::string("hello"), std::string(", world")) << std::endl;

    std::cout << "sum2: " << get_sum2(6, 8) << std::endl;
    std::cout << "sum2: " << get_sum2(6, 8.8) << std::endl;
    //std::cout << "sum2: " << get_sum2(std::string("hello"), std::string(", world")) << std::endl; // // error C2672: "get_sum2":未找到匹配的重载函数

    return 0;
}

      执行结果如下图所示:

      GitHubhttps://github.com/fengbingchun/Messy_Test

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值