C++20的简写函数模板

文章目录

C++20引入了简写函数模板(Abbreviated Function Template),这是一种更简洁的函数模板声明方式,允许使用 auto或带有约束的 auto来代替显式的模板参数声明。

简写函数模板的语法

当在函数参数列表中使用auto或带有约束的auto时,编译器会自动为每个占位符生成一个虚构的模板参数。例如:

cpp 复制代码
void f1(auto); // 等价于 template <class T> void f1(T);
void f2(C1 auto); // 等价于 template <C1 T> void f2(T),如果C1是一个概念(Concept)
void f3(C2 auto...); // 等价于 template <C2... Ts> void f3(Ts...)
void f4(const C3 auto*, C4 auto&); // 等价于 template <C3 T, C4 U> void f4(const T*, U&)

此外,简写函数模板可以像普通函数模板一样进行特化。

示例代码

以下是一个简写函数模板的示例:

cpp 复制代码
namespace {
    auto get_sum(auto a, auto b) {
        return a + b;
    }

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

    auto get_sum2(IntegralOrFloating auto a, IntegralOrFloating auto b) {
        return a + b;
    }
}

int main() {
    std::cout << "Sum: " << get_sum(6, 8) << std::endl; // 输出14
    std::cout << "Sum: " << get_sum(6, 8.8) << std::endl; // 输出14.8
    std::cout << "Sum2: " << get_sum2(6, 8) << std::endl; // 输出14
    std::cout << "Sum2: " << get_sum2(6, 8.8) << std::endl; // 输出14.8
    return 0;
}

在这个例子中,get_sum是一个简写函数模板,可以接受任意类型的参数并返回它们的和。get_sum2则使用了概念(Concept)来限制参数类型,确保它们是整数或浮点数。

优点

简写函数模板的主要优点是语法更加简洁,减少了模板声明的冗余,同时保持了类型安全和灵活性。

如果你对简写函数模板感兴趣,可以参考以下博客和教程:

相关推荐
oioihoii10 天前
C++20 统一容器擦除:std::erase 和 std::erase_if
c++20
郭涤生11 天前
The whole book test_《C++20Get the details》_notes
开发语言·c++·笔记·c++20
郭涤生11 天前
Chapter 6: Concurrency in C++20_《C++20Get the details》_notes
开发语言·c++·笔记·c++20
__lost12 天前
C++20的协程简介
c++20·协程
BanyeBirth12 天前
C++2025年3月等级考试试题(部分)
c++20
点云SLAM13 天前
C++20新增内容
c++·算法·c++20·c++ 标准库
oioihoii14 天前
C++20 的新工具:std::midpoint 和 std::lerp
c++20
郭涤生16 天前
Chapter 1: Historical Context_《C++20Get the details》_notes
开发语言·c++20
郭涤生16 天前
Chapter 5: The Standard Library (C++20)_《C++20Get the details》_notes
开发语言·c++·笔记·c++20
oioihoii20 天前
深入解析 C++20 中的 std::bind_front:高效函数绑定与参数前置
java·算法·c++20