可变参数模板中元函数的最大大小

Max sizeof metafunction in variadic templates

我正在尝试在可变模板中实现一个元函数(?)以在编译时计算几种类型的最大值 sizeof

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);
};

但是我遇到了一些奇怪的错误:

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'

你能帮忙修复我的代码吗?

编译器为MSVC++2017 toolset v141.

std::max 自 C++14 起仅标记为 constexpr,因此您必须自己编写。此外,您不能重载结构,这是您的代码失败的原因之一。

这是一个需要 C++14 std::max 的解决方案,您可以根据需要更改为使用自定义的解决方案。

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

需要 2 个修复:

  1. 正如@Phil1970 所指出的,我忘记了 staticvalue 定义。
  2. 我必须在第 7 行指定模板参数:struct MaxSizeof<T, Ts...> { 而不是简单的 struct MaxSizeof {.

因此编译以下代码:

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);
};

你的专业语法不正确,应该是:

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

需要另一个小修复:

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` 
};