【发布时间】:2016-03-09 19:00:06
【问题描述】:
我正在尝试概括以前在 SO here 上提供的解决方案,它使用 boost MPL 来实例化一个函数的许多模板并在运行时选择正确的模板。我需要的信息可能在互联网上传播,但我自己正在努力拼凑一个可行的解决方案。为了便于阅读,这里是之前解决方案的复制粘贴:
#include <iostream>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/vector_c.hpp>
#include <boost/mpl/for_each.hpp>
#include <boost/mpl/push_back.hpp>
#include <boost/mpl/at.hpp>
namespace mpl = boost::mpl;
template<int index1, int index2, int index3> void execKernel()
{
std::cout << "Kernel called with " << index1 << "/" << index2 << "/" << index3 << std::endl;
}
typedef void (*FPTR)();
FPTR ptr[512];
struct NIL
{
public:
static const int value = 0;
};
template<typename Seq, typename T1, typename T2 = NIL> class MakeSequenceImpl
{
public:
template<typename T> void operator()(T)
{
typedef MakeSequenceImpl<typename mpl::push_back<Seq,T>::type,T2> RunSeq;
mpl::for_each<T1>( RunSeq() );
}
};
template<typename Seq> class MakeSequenceImpl<Seq, NIL, NIL>
{
public:
template<typename T> void operator()(T)
{
typedef typename mpl::push_back<Seq,T>::type FinalSeq;
int index = mpl::at<FinalSeq,mpl::int_<0> >::type::value * 64
+ mpl::at<FinalSeq,mpl::int_<1> >::type::value * 8
+ mpl::at<FinalSeq,mpl::int_<2> >::type::value;
ptr[index] = execKernel<mpl::at<FinalSeq,mpl::int_<0> >::type::value, mpl::at<FinalSeq,mpl::int_<1> >::type::value, mpl::at<FinalSeq,mpl::int_<2> >::type::value>;
}
};
template<typename T0, typename T1, typename T2> class MakeSequence
{
public:
typedef mpl::vector_c<int> Seq;
MakeSequence()
{
typedef MakeSequenceImpl<Seq, T1, T2> RunSeq;
mpl::for_each<T0>( RunSeq() );
}
};
void callWrapper( int i, int j, int k )
{
ptr[i*64+j*8+k]();
}
typedef mpl::vector_c< int, 0, 1, 2, 3, 4, 5, 6, 7 > list1;
typedef mpl::vector_c< int, 0, 1, 2, 3, 4, 5, 6, 7 > list2;
typedef mpl::vector_c< int, 0, 1, 2, 3, 4, 5, 6, 7 > list3;
int main()
{
MakeSequence<list1,list2,list3> frontend;
int i,j,k;
std::cin >> i;
std::cin >> j;
std::cin >> k;
callWrapper(i,j,k);
}
我想将其概括为将“execKernel”作为模板参数传递给“MakeSequence”。我有很多像“execKernel”这样的函数,它们都采用模板参数的数量和相同的类型(都采用 3 个整数模板参数,0-7)。
为此,最终特化“MakeSequenceImpl
总而言之,我希望向下概括“MakeSequence”,以便函数指针数组和函数模板本身作为参数传入。我很高兴为每个特定函数静态定义函数指针和函数指针数组。也可以概括这些(例如,一个包含所有函数的所有函数指针的函数指针的大列表),但这是次要问题。
感谢任何人提供的任何帮助。顺便说一句,我需要继续使用 C++98/03 并提升。没有 C++11 或 14。
【问题讨论】: