动态调度模板功能?

时间:2011-08-17 07:34:11

标签: c++ templates c++11

是否可以在运行时决定调用哪个模板函数? 类似的东西:

template<int I>
struct A {
    static void foo() {/*...*/}
};

void bar(int i) {
    A<i>::f();   // <-- ???
}

5 个答案:

答案 0 :(得分:13)

在处理模板时桥接编译时和运行时的典型“技巧”是访问变体类型。这就是通用图像库(可用作Boost.GIL或独立版)所做的事情。它通常采用以下形式:

typedef boost::variant<T, U, V> variant_type;
variant_type variant = /* type is picked at runtime */
boost::apply_visitor(visitor(), variant);

其中visitor是一个多态函数,只是转发到模板:

struct visitor: boost::static_visitor<> {
    template<typename T>
    void
    operator()(T const& t) const
    { foo(t); } // the real work is in template<typename T> void foo(T const&);
};

这有一个很好的设计,模板将/可以实例化的类型列表(这里,variant_type类型同义词)没有耦合到代码的其余部分。像boost::make_variant_over这样的元功能也允许对要使用的类型列表进行计算。

由于这种技术不适用于非类型参数,因此您需要手动“展开”访问权限,遗憾的是这意味着代码不具有可读性/可维护性。

void
bar(int i) {
    switch(i) {
        case 0: A<0>::f(); break;
        case 1: A<1>::f(); break;
        case 2: A<2>::f(); break;

        default:
            // handle
    }
}

处理上述开关中重复的常用方法是(ab)使用预处理器。使用Boost.Preprocessor的一个(未经测试的)示例:

#ifndef LIMIT
 #define LIMIT 20 // 'reasonable' default if nothing is supplied at build time
#endif
#define PASTE(rep, n, _) case n: A< n >::f(); break;

void
bar(int i) {
    switch(i) {
        BOOST_PP_REPEAT(LIMIT, PASTE, _)

        default:
            // handle
    }
}

#undef PASTE
#undef LIMIT

更好地为LIMIT找到好的,自我记录的名称(也不会对PASTE造成伤害),并将上述代码生成限制为仅一个站点。


根据David的解决方案和您的意见构建:

template<int... Indices>
struct indices {
    typedef indices<Indices..., sizeof...(Indices)> next;
};

template<int N>
struct build_indices {
    typedef typename build_indices<N - 1>::type::next type;
};

template<>
struct build_indices<0> {
    typedef indices<> type;
};

template<int... Indices>
void
bar(int i, indices<Indices...>)
{
    static void (*lookup[])() = { &A<Indices>::f... };
    lookup[i]();
}

然后致电barbar(i, typename build_indices<N>::type())其中N将是您的常数时间常数sizeof...(something)。您可以添加图层以隐藏该通话的“​​丑陋”:

template<int N>
void
bar(int i)
{ bar(i, typename build_indices<N>::type()); }

被称为bar<N>(i)

答案 1 :(得分:8)

根据您想要做的事情(即是否有少量有限的实例化要使用?),您可以创建一个查找表,然后动态使用它。对于完全手动的方法,使用选项0,1,2和3,您可以这样做:

void bar( int i ) {
   static void (*lookup[])(void) = { &A<0>::foo, &A<1>::foo, &A<2>::foo, &A<3>::foo };
   lookup[i]();
}

当然,我为这个例子选择了最简单的选项。如果您需要的数字不是连续的或基于零,您可能更喜欢std::map<int, void (*)(void) >而不是数组。如果要使用的不同选择的数量较大,您可能希望添加代码以自动实例化模板,而不是手动键入所有这些...但您必须考虑模板的每个实例化创建一个新的功能,你可能想检查一下你是否真的需要它。

编辑:我编写了post,仅使用C ++ 03功能实现了相同的初始化,对于答案来说似乎太长了。

Luc Danton写了一个有趣的答案here,其中包括使用C ++ 0x构造初始化查找表。我不太喜欢该解决方案,它将接口更改为需要额外的参数,但可以通过中间调度程序轻松解决。

答案 2 :(得分:4)

不,模板是编译时功能,编译时不知道i,所以这是不可能的。 A<I>::foo()应该适用于A::foo(i)

答案 3 :(得分:1)


模板实现编译时多态,而不是运行时多态。

答案 4 :(得分:1)

模板参数必须在编译时知道。所以编译器无法通过A<i>::foo()

如果您想要解决问题,那么您必须bar() template

template<int i>
void bar() {
    A<i>::f();   // ok
}

为此,您必须在编译时知道bar()的参数。