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

时间:2017-12-14 09:33:10

标签: c++ c++14 metaprogramming template-meta-programming

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

Figure

我有一个类型列表:

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

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

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

1 个答案:

答案 0 :(得分:0)

正如评论所说,检查你的类型有比使用一堆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);