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

相关推荐
Max_uuc11 天前
【架构心法】逃离回调地狱:从 Protothreads 到 C++20 协程 (Coroutines) 的嵌入式进化
c++20
阿猿收手吧!18 天前
【C++】C++20协程的await_transform和coroutine_handle
开发语言·c++·c++20
阿猿收手吧!19 天前
【C++】 co_yield如何成为语法糖?解析其背后的Awaitable展开与协程状态跃迁
c++·c++20
吐泡泡_20 天前
C++20(三路比较运算符)
c++20
啟明起鸣1 个月前
【C++20新特性】概念约束特性与 “模板线程池”,概念约束是为了 “把握未知对象”
开发语言·c++·c++20·模板线程池
linweidong1 个月前
虎牙C++面试题及参考答案(上)
stl·vector·线程·内存管理·c++20·c++面试·c++调用
吐泡泡_1 个月前
C++20(概念和约束)
c++20
訫悦1 个月前
体验在Qt中简单使用C++20的协程
qt·c++20·协程
fpcc1 个月前
C++20中的预处理器宏——__VA_OPT__
c++20
Codeking__1 个月前
C++20的consteval和constinit(接C++11的constexpr)
算法·c++20