Reputation: 1291
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?
Upvotes: 0
Views: 925
Reputation: 66200
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
Upvotes: 1