gpt4 book ai didi

c++ - 可互换使用的类型和非类型模板参数

转载 作者:搜寻专家 更新时间:2023-10-31 00:08:43 25 4
gpt4 key购买 nike

是否可以在 C++ 中声明一些类,以便允许将整数值或类型作为模板参数传递?

像这样:

#include <iostream>
using namespace std;

template <auto I>
struct Foo {};

int main()
{
Foo<int> foo1;
Foo<1> foo2;
return 0;
}

最佳答案

不,那是不可能的。作为解决方法,您可以使用 std::integral_constant 以将值作为类型均匀传递。

template <typename I>
struct Foo {};

int main()
{
Foo<int> foo1;
Foo<std::integral_constant<int, 1>> foo2;
}

使用C++17,你可以定义

template <auto I>
using constant = std::integral_constant<decltype(I), I>;

避免一些样板。

关于c++ - 可互换使用的类型和非类型模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47318363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com