c++ - 在编译时从可能类型的集合中获取整数?

标签 c++ templates c++17

以下代码无法编译,因为我不知道我想做的事情是否可能,但它确实显示了我想要的内容。我在编译时(如果可能的话!)构建类型和整数值的集合;然后在编译时在赋值运算符中使用它,该运算符查看已传递的类型并将集合中的相应整数存储在成员变量 type_ 中:

struct MyStructure {
  MyStructure(char* d, int size) {}

  std::array<pair<TYPE, int>> map {
    { int, 1 },
    { char, 2 },
    { double, 4 },
    { std::string, 8 }
  };

  template <typename T>
  auto operator=(const T &arg) {
    // Depending on the type of 'arg', I want to write a certain value to the member variable 'type_'
  }
  int type_ = 0;
};

int main() {

  MyStructure myStruct;
  myStruct = 1;             // Should cause 1 to be stored in member 'type_ '
  myStruct = "Hello world"; // Should cause 8 to be stored in member 'type_'
}

我需要在 C++17 中解决这个问题;对额外提供 C++20 解决方案的任何人给予额外的尊重,因为这将是一个学习机会!

最佳答案

这是一个基本蓝图,经过一些外观调整后,可以将其插入到您的 MyStructure 中:

#include <string>
#include <iostream>

template<typename T> struct type_map;

template<>
struct type_map<int> {
    static constexpr int value=1;
};

template<>
struct type_map<char> {
    static constexpr int value=2;
};

template<>
struct type_map<double> {
    static constexpr int value=4;
};

template<>
struct type_map<std::string> {
    static constexpr int value=8;
};

template<typename T>
void some_function(const T &arg)
{
    std::cout << type_map<T>::value << std::endl;
}

int main()
{
    some_function(1);                   // Result: 1
    some_function('a');                 // Result: 2
    some_function(std::string{"42"});   // Result: 8
    return 0;
}

关于c++ - 在编译时从可能类型的集合中获取整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73008921/

相关文章:

c++ - 模板类如何继承嵌套模板类

c++ - 为什么 std::optional::operator=(U&&) 要求 U 是非标量类型?

c++ - 将本地时间调整为夏令时 C++

c++ - 将参数传递给父类(super class)构造函数

C++ 模板化、静态分配的数组

c++ - 是否有可能获得未知类的类成员的数量和类型?

c++ - 自 C++17 的类模板参数推导以来,std::make_move_iterator 是否多余?

c++ - 是否可以在 Qt 的顶级窗口之间使用相同的 OpenGL 上下文?

android - NDK c++ 从文件 Android 加载着色器

c++ - is_greater_than 模板元编程