Serge Rogatch
Serge Rogatch

Reputation: 15040

Max sizeof metafunction in variadic templates

I'm trying to implement a metafunction(?) in variadic templates to calculate the max of sizeof of a few types at compile-time.

template<typename... Ts> struct MaxSizeof {
  static constexpr size_t value = 0;
};

template<typename T, typename... Ts> struct MaxSizeof {
  static constexpr size_t value = std::max(sizeof(T), typename MaxSizeof<Ts...>::value);
};

But I'm getting a few strange errors:

MaxSizeof.h(7): error C3855: 'MaxSizeof': template parameter 'Ts' is incompatible with the declaration
MaxSizeof.h(7): error C2977: 'MaxSizeof': too many template arguments
MaxSizeof.h(5): note: see declaration of 'MaxSizeof'

Could you help fixing my code?

The compiler is MSVC++2017 toolset v141.

Upvotes: 0

Views: 559

Answers (4)

pepero
pepero

Reputation: 7513

another minor fix needed:

template<typename T, typename... Ts> struct MaxSizeof<T, Ts...> {
  static constexpr size_t value = std::max(sizeof(T), MaxSizeof<Ts...>::value); // there should be with no `typename` 
};

Upvotes: 0

Jarod42
Jarod42

Reputation: 217293

Your specialization has not correct syntax, it should be:

template<typename T, typename... Ts>
struct MaxSizeof<T, Ts...> { // Note the <T, Ts...> here
    // ....
};

Upvotes: 3

Serge Rogatch
Serge Rogatch

Reputation: 15040

There were 2 fixes needed:

  1. As pointed out by @Phil1970 , I forgot static for value definition.
  2. I had to specify template arguments on line 7: struct MaxSizeof<T, Ts...> { instead of simply struct MaxSizeof {.

So the following code compiles:

template<typename... Ts> struct MaxSizeof {
  static constexpr size_t value = 0;
};

template<typename T, typename... Ts> struct MaxSizeof<T, Ts...> {
  static constexpr size_t value = std::max(sizeof(T), typename MaxSizeof<Ts...>::value);
};

Upvotes: 0

Rakete1111
Rakete1111

Reputation: 48958

std::max is only marked constexpr since C++14, so you will have to write your own. Also, you can't overload structs, which is one reason why your code fails.

Here's a solution requiring C++14's std::max, which you can change to use a custom one as required.

template<typename... Ts>
struct MaxSizeof : std::integral_constant<std::size_t, std::max({sizeof(Ts)...})> {};

Upvotes: 0

Related Questions