Reputation: 15040
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
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
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
Reputation: 15040
There were 2 fixes needed:
static
for value
definition.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
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