C++20中支持的非类型模板参数

C++20中支持将类类型作为非类型模板参数:作为模板参数传入的对象具有const T类型 ,其中T是对象的类型,并且具有静态存储持续时间(static storage duration)。

在C++20之前,非类型模板参数仅限于:左值引用类型、整数类型、指针类型、指向成员类型的指针、枚举类型、std::nullptr_t。在C++20中,它已扩展并支持:浮点类型、字面量类类型(literal class type)。

测试代码如下:

cpp 复制代码
namespace {
template<int N> // int non-type template parameter
struct Array {
	static_assert(N > 0, "N must be greater than 0");
	int data[N];
};

template<float v> // c++20
void print_value()
{
	static_assert(v < 0, "v must be less than 0");
	std::cout << "v: " << v << std::endl;
}

// literal class type
struct Foo {
	constexpr Foo() {}
	constexpr Foo(int value): has_value(true), value(value) {}

	const int value{};
	const bool has_value{ false };
};

template <Foo f> // c++20
void print_foo() {
	if constexpr (f.has_value)
		std::cout << "value: " << f.value << std::endl;
	else
		std::cout << "no value" << std::endl;
}

} // namespace

int test_template_20()
{
	Array<5> arr;
	arr.data[3] = {6};
	std::cout << "arr[3]: " << arr.data[3] << std::endl;

	print_value<-1.1f>();

	print_foo < Foo{ 66 } > ();
	print_foo < Foo{} > ();

	return 0;
}

执行结果如下图所示:

GitHubhttps://github.com/fengbingchun/Messy_Test

相关推荐
a东方青11 天前
[蓝桥杯C++ 2024 国 B ] 立定跳远(二分)
c++·算法·蓝桥杯·c++20
小葡萄202513 天前
黑马程序员2024新版C++笔记 第五章 面向对象
开发语言·c++·笔记·c++20
Tipriest_15 天前
【C++20新特性】ranges::sort()使用方法,优势,注意点
算法·leetcode·c++20·排序·sort
Tipriest_15 天前
ubuntu20.04&vscode使用C++20(调整gcc版本&vscode设置)
ide·vscode·c++20·gcc
小葡萄202515 天前
黑马程序员C++2024新版笔记 第4章 函数和结构体
笔记·c++20
AI迅剑17 天前
《C++20新特性全解析:模块、协程与概念(Concepts)》
c++20
superior tigre21 天前
C++学习:六个月从基础到就业——C++20:范围(Ranges)进阶
c++·学习·c++20
superior tigre21 天前
C++学习:六个月从基础到就业——C++20:范围(Ranges)基础
c++·学习·c++20
点云SLAM22 天前
C++中聚合类(Aggregate Class)知识详解和注意事项
c++·算法·c++20·c++学习·聚合类·面向对象设计、·c++高级应用
小葡萄202522 天前
黑马程序员C++2024新版笔记 第三章 数组
笔记·算法·c++20