c++ - 模板类默认类型和条件

标签 c++ templates default enable-if conditional-types

我想对 MyClass 使用 std::enable_if 以便仅接受 (uint32_t | uint64_t) 并且同时如果用户未提供任何类型;根据以下条件选择默认值。

但我无法让它工作。 (C++17)

#include <vector>
#include <cstdint>

template <typename T=std::conditional_t<sizeof(void*) == 8, std::uint64_t, std::uint32_t>>
class MyClass
{
  private:
    std::vector<T> vs;
  public:
  // ...
};


int main(){
  MyClass a; // OK, the defaut type is used either uint32_t or uint64_t
  MyClass<std::uint32_t> b; // Ok, use the user provided type
  MyClass<long> c; // must not compile, T is not one of uint32_t, uint64_t
}

最佳答案

您可以添加static_assert执行检查。

template <typename T=std::conditional_t<sizeof(void*) == 8, std::uint64_t, std::uint32_t>>
class MyClass
{
  static_assert(std::is_same_v<T, std::uint64_t> || std::is_same_v<T, std::uint32_t>, "T must be std::uint64_t or std::uint32_t");
  private:
    std::vector<T> vs;
  public:
  // ...
};

LIVE

关于c++ - 模板类默认类型和条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59703844/

相关文章:

c++ - 有谁知道 ziplib 是否能够在不实际提取所有文件的情况下验证 zip 库

c++ - 如何在 C++ 中为实例化的模板类编写 header ?

sql-server - 默认登录用户到 SQL Server 列

haskell - 在 Haskell 中,是否可以为部分应用的多参数类型类提供默认实现?

c++ - 何时使用 reinterpret_cast?

c++ - 释放字符指针

c++ - 在 gdb 中 : During startup program exited with code 1. 在 GDB 之外运行良好

c++ - 如何使特征接受参数包?

c++ - 了解模板内定义的模板 (C++)

android - 如何设置 DefaultSharedPreferences 值?