【问题标题】:Most simple way of generating if-else from compile-time types从编译时类型生成 if-else 的最简单方法
【发布时间】:2017-12-14 09:33:09
【问题描述】:

我正在使用 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 结构而仅仅依靠重载来执行特定于类型的行为吗?即 void do_stuff(T thing) {...} void do_stuff(U thing) {...}` 等
  • if-else 链在区块中会做什么?
  • 添加到重载列表与添加到任何其他形式的“按类型选择的操作列表”有何不同?
  • 这个 if/else 序列没有做任何事情。因此,一个空程序可以解决您的问题。可能您打算出于某种目的在条件下做某事,但这在问题中并不明显:澄清问题,而不是 cmets。作为猜测,你真的想要一个变体或类似的东西。
  • edit 问题并显示实际执行某些操作的代码。什么都不做的代码不能说明问题。无论如何,您似乎需要 std::variant 和 std::visit 或它们的 Boost 对应物。

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


【解决方案1】:

正如 cmets 所说,有比使用一堆 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);

【讨论】:

    猜你喜欢
    • 2023-04-05
    • 2018-10-20
    • 1970-01-01
    • 2021-09-29
    • 2012-03-31
    • 2018-12-13
    • 1970-01-01
    • 1970-01-01
    • 2011-02-01
    相关资源
    最近更新 更多