简体   繁体   中英

C++ template parameter that accepts a value OR a type

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM