gpt4 book ai didi

c++ - 使用typeid来处理不同的类型

转载 作者:IT王子 更新时间:2023-10-29 06:21:37 25 4
gpt4 key购买 nike

我正在尝试使用 boost::any 来封装 sqlite 返回值。然后我尝试编写一个循环来打印这些。

我的第一个想法是做这样的事情:

for(boost::any field: row) {
switch(field.type()) {
case typeid(double):
double value = any_cast<double>(field);
...
break;
case typeid(other type):
...
}
}

现在,对于有经验的程序员来说,这很明显是行不通的,因为 typeid 返回一个实例而不是数字 id。经过一些研究,我想我可以试试 typeid(...).hash_code()然而这还不够constexpr合格(除了散列冲突的危险)。

问题

  1. 有没有比构建过多的更好的方法 if ... else ...根据 typeid 处理对象的迷宫?
  2. hash_code有什么原因吗?不是 const_expr ?这是目标文件单独编译的结果吗?
  3. std::type_index有什么用?考虑到它只提供了一些额外的运算符( <<=>>= ),为什么不能将其功能与 std::type_info 集成? ?

最佳答案

我感觉您正在寻找 boost 变体和静态访问。

由于未提及变体,这可能值得作为答案发布。示范:

Live On Coliru

#include <sstream>
#include <iostream>

#include <boost/variant.hpp>

using namespace boost;

struct Nil {};
using blob_t = std::vector<uint8_t>;
using field_value_t = boost::variant<Nil, double, char const*, long, blob_t/*, boost::date_time, std::vector<uint8_t>*/>;

struct handler : static_visitor<std::string> {

std::string operator()(double) const { return "double"; }
std::string operator()(char const*) const { return "C string (ew!)"; }
std::string operator()(long) const { return "long"; }
std::string operator()(blob_t) const { return "long"; }
std::string operator()(Nil) const { return "<NIL>"; }

template<typename T>
std::string operator()(T const&) const { throw "Not implemented"; } // TODO proper exception
};

void handle_field(field_value_t const& value) {
std::cout << "It's a " << apply_visitor(handler(), value) << "\n";
}

int main() {

handle_field({});
handle_field(blob_t { 1,2,3 });
handle_field("Hello world");
handle_field(3.14);

}

打印

It's a <NIL>
It's a long
It's a C string (ew!)
It's a double

关于c++ - 使用typeid来处理不同的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27368588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com