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

相关推荐
bkspiderx2 天前
C++时区操作全版本指南(含C++03/C++11-17/C++20)
linux·开发语言·c++·c++20·时区
黄贵根2 天前
C++20 基于文本文件的类对象增删查改系统
算法·c++20
木心爱编程2 天前
C++20多线程新特性:更安全高效的并发编程
java·jvm·c++20
抓饼先生3 天前
C++ 20 视图view笔记
linux·开发语言·c++·笔记·c++20
郝学胜-神的一滴4 天前
深入浅出 C++20:新特性与实践
开发语言·c++·程序人生·算法·c++20
_不会dp不改名_23 天前
C++ 20: Concepts 与Requires
开发语言·c++20
arbboter1 个月前
【C++20】新特性探秘:提升现代C++开发效率的利器
c++·c++20·新特性·span·结构化绑定·初始化变量·模板参数推导
猿饵块1 个月前
c++20--std::format
c++20
mrbone112 个月前
C++-关于协程的一些思考
开发语言·数据库·c++·c++20·协程·异步·coroutines
xiaolang_8616_wjl2 个月前
c++文字游戏_闯关打怪
开发语言·数据结构·c++·算法·c++20