C++接受值或类型的模板参数

发布于 2025-02-10 05:16:52 字数 573 浏览 0 评论 0原文

我正在尝试使用接受值和类型作为有效载荷的模板来创建一个简单的堆栈:

// type that marks end of stack
struct StackEmptyNode {};

// 
template<auto Value, typename T = StackEmptyNode>
struct StackNode {};

使用自动值允许我声明堆栈具有诸如stackNode&lt; 3,stackNode&lt之类的值; 4,stacknode&lt; 9&gt;&gt ;;

但是我也想遇到相同的堆栈以接受与有效载荷的类型。这可以通过将自动值更改为模板值来完成,它允许我声明stackNode&lt; int,stacknode&lt; float,stacknode,stacknode&lt; std :: string&gt;&gt;&gt;&gt; &gt ;;

我希望能够用于相同的stackNode实现。使用模板可以使用吗?

I'm attempting to create a simple stack using templates that accepts both values and types as the payload:

// type that marks end of stack
struct StackEmptyNode {};

// 
template<auto Value, typename T = StackEmptyNode>
struct StackNode {};

The use of auto Value allows me to declare stacks with values such as StackNode<3, StackNode<4, StackNode<9>>>;

However I also want to the same stack to accept types as the payload. This can be done by changing auto Value to template Value which allows me to declare StackNode<int, StackNode<float, StackNode<std::string>>>;.

I want to be able to use either for the same StackNode implementation. Is this possible using templates?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我不咬妳我踢妳 2025-02-17 05:16:52

我希望能够将任何一种用于同一堆栈诺德实现。是否可以使用模板?

简短答案:否。

很长的答案。
我能想象的最好的方法是使用(以示例)标准std :: Integral_constant类使用类型中的类型和包装值。

因此,您可以写一些

StackNode<int, StackNode<std::integral_constant<int, 4>, StackNode<std::string>>>;
//.......................^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^  the value 4 become a class

新的(C ++ 17)auto“值”设施,您可以简化一些写入简单的值包装器

template<auto>
value_wrapper
{ };

,以便避免值的类型

StackNode<int, StackNode<value_wrapper<4>, StackNode<std::string>>>;
// ......................^^^^^^^^^^^^^^^^  now 4 is simply 4, without it's type

I want to be able to use either for the same StackNode implementation. Is this possible using templates?

Short answer: no.

Long answer.
The best I can imagine is to use types and wrap values inside types, using (by example) the standard std::integral_constant class.

So you can write something as

StackNode<int, StackNode<std::integral_constant<int, 4>, StackNode<std::string>>>;
//.......................^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^  the value 4 become a class

Using the new (C++17) auto value facility, you can simplify a little writing a simple value wrapper

template<auto>
value_wrapper
{ };

so you can avoid the type of the value

StackNode<int, StackNode<value_wrapper<4>, StackNode<std::string>>>;
// ......................^^^^^^^^^^^^^^^^  now 4 is simply 4, without it's type
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文