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

相关推荐
十五年专注C++开发15 天前
全面深入了解C++20 范围库(std::ranges)
c++20·管道·哨兵·视图·ranges
小小龙学IT17 天前
C++20 协程深度解析:从原理到高性能异步框架实战
junit·c++20
楼田莉子22 天前
C++20新特性:协程
开发语言·c++·后端·学习·c++20
ouliten24 天前
C++笔记:C++20风格线程池
c++·笔记·c++20
眠りたいです1 个月前
现代C++:C++17中的新库特性
开发语言·c++·c++20·c++17
楼田莉子1 个月前
C++20新特性:Range库
开发语言·c++·后端·学习·c++20
楼田莉子1 个月前
C++20现代特性:概念与约束
开发语言·c++·后端·学习·c++20
aluluka1 个月前
C++ 20 协程的探索
c++·c++20
君鼎1 个月前
内存池完整实现——C++20版
c++20·内存池
普通网友2 个月前
记录我适配iOS26遇到的一些问题
c++20