欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > C++20中支持的非类型模板参数

C++20中支持的非类型模板参数

2024/10/24 20:20:27 来源:https://blog.csdn.net/fengbingchun/article/details/141994463  浏览:    关键词:C++20中支持的非类型模板参数

      C++20中支持将类类型作为非类型模板参数:作为模板参数传入的对象具有const T类型,其中T是对象的类型,并且具有静态存储持续时间(static storage duration)。

      在C++20之前,非类型模板参数仅限于:左值引用类型、整数类型、指针类型、指向成员类型的指针、枚举类型、std::nullptr_t。在C++20中,它已扩展并支持:浮点类型、字面量类类型(literal class type)。

      测试代码如下:

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;elsestd::cout << "no value" << std::endl;
}} // namespaceint 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;
}

      执行结果如下图所示:

      GitHub:https://github.com/fengbingchun/Messy_Test

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com