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