从编译时类型生成 if-else 的最简单方法

Most simple way of generating if-else from compile-time types

我正在使用 C++14。我想以最简单的方式为编译时已知的一组类型生成此代码结构:

if (myinstance.type() == typeid(T)) {

}
else if (myinstance.type() == typeid(U)) {

}...

我有一个类型列表:

using MyTypes = std::tuple<int, float, OtherType, OneMoreType>

我想这样做:

template <class TList>
void generateIfElses(Object & myinstance);

并像这样使用:

generateIfElses<MyType>(instance);

我有一个解决方案,但我发现它很脏:它意味着一个具有 2 个特化的辅助结构加上一个具有 std::index_sequence 支持的函数。

从类型列表获得此代码结构的最简单方法是什么?

正如评论所说,有比使用一堆 if-else 语句更好的方法来检查您的类型,但如果您真的想走这条路,这里有一些代码可以做到这一点。我留了一些空的部分供你填写,这取决于找到类型时需要采取什么行动。该代码使用了 boost.mp11 库(参见 here

#include <boost/mp11.hpp>

using namespace boost::mp11;

template <class TList, class Size = mp_size<TList>>
struct ifelse {

    using head_type = mp_first<TList>;
    using tail_type = mp_pop_front<TList>;

    template <class X>
    static void call(X& x) {

        if(x.type() == typeid(head_type)) {
            // your object type is found, do something interesting here
        }
        else ifelse<tail_type, mp_size<tail_type>>::call(x);
    }
};

// specialisation for empty typelist
template <class TList>
struct ifelse<TList, mp_size_t<0>> {

    template <class X>
    static void call(X& x) {
        // your object type was not found in the typelist, deal with it here
    }
};

你可以这样使用它:

ifelse< std::tuple<int, float, double> >::call(instance);