【发布时间】:2014-02-09 20:04:55
【问题描述】:
我一直在使用tag dispatching 来模拟问题。
注意:这段代码运行,我只是对不涉及太多编码的解决方案感兴趣,只是为了反转调度算法的参数。
这里是有问题的代码:
#include <iostream>
struct A_tag {};
struct B_tag {};
// Tag getter
template<typename Type>
struct get { typedef void tag; };
namespace dispatch {
template<typename T1, typename T2>
struct my_algorithm {};
template<>
struct my_algorithm<A_tag, B_tag>
{
template<typename P1, typename P2>
static void apply(P1 const& p1, P2 const& p2)
{
auto p1val = p1.value();
auto p2val = p2.someFunction();
std::cout << p1val << " " << p2val << std::endl;
}
};
//Specialization reversal: can this be made shorter?
//A lot of lines used just to reverse the algorithm.
template<>
struct my_algorithm<B_tag, A_tag>
{
template<typename P2, typename P1>
static void apply(P2 const & p2, P1 const & p1)
{
my_algorithm<typename get<P1>::tag, typename get<P2>::tag>::apply(p1, p2);
}
};
}
// First and Second are test classes.
class First
{
public:
double value() const { return 5; };
};
template<>
struct get<First>
{
typedef A_tag tag; // Expect First to behave as A
};
class Second
{
public:
double someFunction() const { return 6; };
};
template<>
struct get<Second>
{
typedef B_tag tag; // Expect Second behave as B
};
// Tag dispatcher.
template<typename P1, typename P2>
void my_algorithm(P1 const & p1, P2 const & p2)
{
dispatch::my_algorithm<typename get<P1>::tag, typename get<P2>::tag>::apply(p1, p2);
}
int main(int argc, const char *argv[])
{
First f;
Second s;
my_algorithm(f, s);
// Commutative algorithm.
my_algorithm(s,f);
return 0;
}
无论模板参数的顺序如何,一些分派算法的工作方式都是一样的。 dispatch::my_algorithm::apply 函数完成了本示例中的所有工作。我已经设法使用 dispatch::my_algorithm 类的完整模板专业化来反转模板参数,并使用反转参数调用静态 apply 函数。
可以更快地进行参数反转吗?即使我设法打包并“调用它”,当apply 接受更多参数时,其他算法会发生什么?
【问题讨论】:
标签: c++ templates template-specialization