LyingOnTheSky
LyingOnTheSky

Reputation: 2854

How can this condition be put in template partial specialization?

template<size_t bits_count, typename = void>
struct best_type {
};

template<size_t bits_count>
struct best_type<bits_count,enable_if_t<bits_count > 8>> { // error: template argument 2 is invalid
  typedef byte type;
};

The error is because of the parser sees the second template argument as enable_if_t<bits_count > following a random 8.

Obviously the solution to this can be replacing the argument of enable_if_t to bits_count >= 9, but can something be done to preserve the original expression so it will make sense to future readers?

Upvotes: 0

Views: 92

Answers (2)

Curious
Curious

Reputation: 21510

Put the condition in parentheses.

template<size_t bits_count, typename = std::enable_if_t<true>>
struct best_type {
};

template<size_t bits_count>
struct best_type<bits_count, std::enable_if_t<(bits_count > 8)>> {
    using type = byte;
};

Also note that I have replaced the void with std::enable_if_t<true>, since it makes more sense to the reader.

Also note that it is better to use using aliases (as compared to typedefs) in C++

Upvotes: 1

Edgar Rokjān
Edgar Rokjān

Reputation: 17483

You should add additional parentheses to explain the compiler what you mean:

template<size_t bits_count>
struct best_type<bits_count,enable_if_t<(bits_count > 8)>> {
    typedef byte type;
};

Upvotes: 4

Related Questions