c++ - 在模板和非模板代码之间进行交互时替换 switch 语句

标签 c++ templates c++11

X:

我看到的一个常见模式是函数的底层代码是模板,但由于“原因”,模板代码在上层不可用(从界面中对模板的厌恶中选择,需要共享库而不是向客户公开实现,在运行时而不是编译时读取类型设置等)。

这通常会产生以下结果:

struct foo { virtual void foo() = 0;}
template <typename T> struct bar : public foo
{
    bar( /* Could be lots here */);
    virtual void foo() { /* Something complicated, but type specific */}
};

然后是初始化调用:

foo* make_foo(int typed_param, /* More parameters */)
{
    switch(typed_param)
    {
        case 1: return new bar<int>(/* More parameters */);
        case 2: return new bar<float>(/* More parameters */);
        case 3: return new bar<double>(/* More parameters */);
        case 4: return new bar<uint8_t>(/* More parameters */);
        default: return NULL;
    }
}

这是令人讨厌、重复且容易出错的代码。

所以我对自己说,我自己说,一定有更好的方法。

Y:

这是我做的。大家有更好的办法吗?

////////////////////////////////////
//////Code to reuse all over the place
///
template <typename T, T VAL>
struct value_container
{
    static constexpr T value() {return VAL;}
};

template <typename J, J VAL, typename... Ts>
struct type_value_pair
{
    static constexpr J value() {return VAL;}

    template <class FOO>
    static auto do_things(const FOO& foo)->decltype(foo.template do_things<Ts...>()) const
    {
        foo.template do_things<Ts...>();
    }
};

template <typename T>
struct error_select
{
    T operator()() const { throw std::out_of_range("no match");}
};

template <typename T>
struct default_select
{
    T operator()() const { return T();}
};

template <typename S, typename... selectors>
struct type_selector
{
    template <typename K, class FOO, typename NOMATCH, typename J=decltype(S::do_things(FOO()))>
    static constexpr J select(const K& val, const FOO& foo=FOO(), const NOMATCH& op=NOMATCH())
    {
        return S::value()==val ? S::do_things(foo) : type_selector<selectors...>::template select<K, FOO, NOMATCH, J>(val, foo, op);
    }
};

template <typename S>
struct type_selector<S>
{
    template <typename K, class FOO, typename NOMATCH, typename J>
    static constexpr J select(const K& val, const FOO& foo=FOO(), const NOMATCH& op=NOMATCH())
    {
        return S::value()==val ? S::do_things(foo) : op();
    }
};

////////////////////////////////////
////// Specific implementation code
class base{public: virtual void foo() = 0;};

template <typename x>
struct derived : public base
{
    virtual void foo() {std::cout << "Ima " << typeid(x).name() << std::endl;}
};


struct my_op
{
    template<typename T>
    base* do_things() const
    {
        base* ret = new derived<T>();
        ret->foo();
        return ret;
    }
};

int main(int argc, char** argv)
{
    while (true)
    {
        std::cout << "Press a,b, or c" << std::endl;
        char key;
        std::cin >> key;

        base* value = type_selector<
            type_value_pair<char, 'a', int>,
            type_value_pair<char, 'b', long int>,
            type_value_pair<char, 'c', double> >::select(key, my_op(), default_select<base*>());

        std::cout << (void*)value << std::endl;
    }

    /* I am putting this in here for reference. It does the same
       thing, but the old way: */

    /*
        switch(key)
        {
            case 'a':
              {
                  base* ret = new derived<int>();
                  ret->foo();
                  value = ret;
                  break;
              }

            case 'b':
              {
                  base* ret = new derived<char>();
                  ret->foo();
                  value = ret;
                  break;
              }

            case 'c':
              {
                  base* ret = new derived<double>();
                  ret->foo();
                  value = ret;
                  break;
              }

            default:
                return NULL;
        }
    */
}

我在实现中发现的问题:

  1. 像泥巴一样清晰易读
  2. 模板参数必须是类型,必须将值封装在类型中 ( template <typename T, T VAL> struct value_container { static constexpr T value() {return VAL;} }; )
  3. 目前没有检查/强制选择器都是类型值对。

唯一的优点:

  1. 删除重复代码。
  2. 如果 case 语句变高/do_things 的内容变高,那么我们可以短一点。

有人做过类似的事情或者有更好的方法吗?

最佳答案

您始终可以遍历由 type_param 索引的类型列表,如下所示:

struct foo 
{
    virtual ~foo() = default;
    /* ... */
};

template<typename T>
struct bar : foo 
{ /* ... */ };


template<typename TL> 
struct foo_maker;

template<template<typename...> class TL, typename T, typename... Ts> 
struct foo_maker<TL<T, Ts...>>
{
    template<typename... Us>
    std::unique_ptr<foo> operator()(int i, Us&&... us) const
    {
        return i == 1 ?
            std::unique_ptr<foo>(new bar<T>(std::forward<Us>(us)...)) :
            foo_maker<TL<Ts...>>()(i - 1, std::forward<Us>(us)...); }
};

template<template<typename...> class TL> 
struct foo_maker<TL<>>
{
    template<typename... Us>
    std::unique_ptr<foo> operator()(int, Us&&...) const
    { return nullptr; }
};


template<typename...>
struct types;


template<typename... Us>
std::unique_ptr<foo> make_foo(int typed_param, Us&& us...)
{ return foo_maker<types<int, float, double, uint8_t>>()(typed_param, std::forward<Us>(us)...); };

注意:这个工厂函数的复杂度为 O(n)(尽管聪明的编译器可以使其复杂度为 O(1)),而 switch 语句的复杂度为 O(1)。

关于c++ - 在模板和非模板代码之间进行交互时替换 switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23092121/

相关文章:

c++ - 从 calloc() 迁移到 new

c++ - 关于 C++ 中 std::promise 的错误

c++ - 避免对非虚拟析构函数进行对象切片

c++ - 通过枚举重载模板化成员函数

c++ - 在另一个命名空间中定义一个符号

c++ - 编译时计算头文件中的常量

c++ - 常量表达式中不能使用未知值的函数参数

c++ - 当使用复制构造函数为持有它的变量分配一个新对象时,前一个对象是否被销毁?

c++ - 通过构造函数初始化 unique_ptr

c++ - 在 C++ 中如何直接初始化对象?