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

相关推荐
Ethan Wilson13 小时前
VS2019 C++20 模块相关 C1001: 内部编译器错误
开发语言·c++·c++20
DYS_房东的猫15 小时前
《 C++ 零基础入门教程》第10章:C++20 核心特性 —— 编写更现代、更优雅的 C++
java·c++·c++20
ice_junjun11 天前
C++20 线程返回值处理指南
c++20·c++ 多线程返回值
凌乱风雨121114 天前
从源码角度解析C++20新特性如何简化线程超时取消
前端·算法·c++20
shuai132_23 天前
【无标题】
c++20
ULTRA??25 天前
基于range的函数式编程C++,python比较
c++·python·kotlin·c++20
apocelipes25 天前
从源码角度解析C++20新特性如何简化线程超时取消
c++·性能优化·golang·并发·c++20·linux编程
ALex_zry1 个月前
C++20和C++23 在内存管理、并发控制和类型安全相关优化方式的详细技术分析
安全·c++20·c++23
ALex_zry1 个月前
C++20/23标准对进程间共享信息的优化:从传统IPC到现代C++的演进
开发语言·c++·c++20
fpcc1 个月前
c++20容器中的透明哈希
哈希算法·c++20