C++接受值或类型的模板参数
我正在尝试使用接受值和类型作为有效载荷的模板来创建一个简单的堆栈:
// 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简短答案:否。
很长的答案。
我能想象的最好的方法是使用(以示例)标准
std :: Integral_constant
类使用类型中的类型和包装值。因此,您可以写一些
新的(C ++ 17)
auto
“值”设施,您可以简化一些写入简单的值包装器,以便避免值的类型
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
Using the new (C++17)
auto
value facility, you can simplify a little writing a simple value wrapperso you can avoid the type of the value