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

相关推荐
郭涤生5 天前
Concepts (C++20)
c++20
chendilincd6 天前
C++ 的史诗级进化:从C++98到C++20
java·c++·c++20
oioihoii22 天前
C++20 统一容器擦除:std::erase 和 std::erase_if
c++20
郭涤生22 天前
The whole book test_《C++20Get the details》_notes
开发语言·c++·笔记·c++20
郭涤生22 天前
Chapter 6: Concurrency in C++20_《C++20Get the details》_notes
开发语言·c++·笔记·c++20
__lost23 天前
C++20的协程简介
c++20·协程
BanyeBirth23 天前
C++2025年3月等级考试试题(部分)
c++20
点云SLAM24 天前
C++20新增内容
c++·算法·c++20·c++ 标准库
oioihoii25 天前
C++20 的新工具:std::midpoint 和 std::lerp
c++20
郭涤生1 个月前
Chapter 1: Historical Context_《C++20Get the details》_notes
开发语言·c++20