使用typeid处理不同类型

ted*_*ted 9 c++ sqlite boost boost-any

我试图使用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):
          ...
  }
}
Run Code Online (Sandbox Code Playgroud)

现在对于有经验的程序员来说,显然这不起作用,因为typeid返回实例而不是数字id.经过一些研究,我认为我可能会尝试,typeid(...).hash_code()但这不足够constexpr合格(除了哈希冲突的危险).

问题

  1. 有没有比建立一个过度的if ... else ...迷宫更好的方法来处理基于他们的typeid的对象?
  2. 有没有理由hash_code不是const_expr?这是单独编译目标文件的结果吗?
  3. 有什么用std::type_index?考虑到它只是提供了一些额外的运营商(<,<=,>,>=),为什么却无法其功能与整合std::type_info

seh*_*ehe 7

我有一种感觉,你正在寻找提升变量和静态访问.

由于没有提到变体,这可能值得作为答案发布.Demonstruction:

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

}
Run Code Online (Sandbox Code Playgroud)

打印

It's a <NIL>
It's a long
It's a C string (ew!)
It's a double
Run Code Online (Sandbox Code Playgroud)


cdh*_*wie 5

这是一个类似于静态访问的实现boost::any,使用C++ 11 lambdas:

#include <iostream>
#include <type_traits>
#include <boost/any.hpp>

template <size_t, typename...>
struct select_type { };

template <size_t index, typename First, typename... Types>
struct select_type<index, First, Types...> : public select_type<index - 1, Types...> { };

template <typename First, typename... Types>
struct select_type<0, First, Types...>
{
    using type = First;
};

template <typename T>
struct function_traits : public function_traits<decltype(&T::operator())> { };

template <typename Return, typename Class, typename... Args>
struct function_traits<Return (Class::*)(Args...) const>
{
    using result_type = Return;

    template <size_t argN>
    using argument_type = select_type<argN, Args...>;
};

template <typename... Functors>
struct any_call_impl
{
    static bool call(boost::any &, Functors const & ...)
    {
        return false;
    }

    static bool call(boost::any const &, Functors const & ...)
    {
        return false;
    }
};

template <typename FirstFunctor, typename... Functors>
struct any_call_impl<FirstFunctor, Functors...>
{
    static bool call(boost::any & v, FirstFunctor const & first, Functors const & ... rest)
    {
        using arg = typename function_traits<FirstFunctor>::template argument_type<0>::type;
        using arg_bare = typename std::remove_cv<typename std::remove_reference<arg>::type>::type;

        if (v.type() == typeid(arg_bare)) {
            first(*boost::any_cast<arg_bare>(&v));
            return true;
        }

        return any_call_impl<Functors...>::call(v, rest...);
    }

    static bool call(boost::any const & v, FirstFunctor const & first, Functors const & ... rest)
    {
        using arg = typename function_traits<FirstFunctor>::template argument_type<0>::type;
        using arg_bare = typename std::remove_cv<typename std::remove_reference<arg>::type>::type;

        if (v.type() == typeid(arg_bare)) {
            first(*boost::any_cast<arg_bare>(&v));
            return true;
        }

        return any_call_impl<Functors...>::call(v, rest...);
    }
};

template <typename... Functors>
bool any_call(boost::any & v, Functors const & ... f)
{
    return any_call_impl<Functors...>::call(v, f...);
}

template <typename... Functors>
bool any_call(boost::any const & v, Functors const & ... f)
{
    return any_call_impl<Functors...>::call(v, f...);
}

int main(void) {
    boost::any a = 1;

    any_call(a,
        [](double d) { std::cout << "double " << d << std::endl; },
        [](int i) { std::cout << "int " << i << std::endl; }
    );

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

(演示)

这个想法是你传递一个boost::anyboost::any const作为第一个参数any_call,然后传递多个lambdas.boost::any将调用其参数类型与包含的对象类型匹配的第一个lambda ,然后any_call返回true.如果没有lambda匹配,any_call则返回false.