quant
quant

Reputation: 23052

Can I template the type of a template value parameter?

Suppose I want to create a struct that converts the value of an enum to a meta int, such as boost::mpl::int_. I could do something like this:

template <typename Enum, Enum value>
struct Convert
{
  using type = boost::mpl::int_<static_cast<int>(value)>;
};

This would work fine, but to call it I'd have to write Convert<Enum, Enum::VALUE>::type. Is it possible to write a class so I simply have to write Convert<Enum::VALUE>::type to have Convert deduce the type of Enum?

I don't know the type of Enum, so Convert should be able to take any enum. I'd like to avoid macros.

Upvotes: 0

Views: 62

Answers (1)

StilesCrisis
StilesCrisis

Reputation: 16290

Functions can deduce template parameters; classes cannot. That's why std has functions like make_pair as a complement to the pair class.

You can use a similar strategy.

For instance, you can declare a templated Convert function and then extract its return type via decltype(Convert<Enum::VALUE>()).

Upvotes: 2

Related Questions