我在命名空间N中有一个类C,其公共模板成员函数F如下:
namespace N {
class C {
public:
template<int I>
void F() {
// ...
}
};
};
I
for的值N::C::F<I>
直到运行时才知道。但是,的值I
受到限制,使得0 <= I < 2^8
。我正在寻找一种强制此功能将模板扩展到所有256种可能形式的方法。
到目前为止,我已经在第二个函数中手动创建了一个静态数组,该数组C
指向每个可能的函数:
template<int I>
void F() {
// ...
}
void G(int I) {
static void(* const funcs[256])() = {
F<0>, F<1>, F<2>, ...
};
funcs[I]();
}
尽管我想知道是否有更好的方法。我已经有了一个宏,N
该宏负责为每个值构造一个单独的结构I
(供F本身使用),并正在寻找是否可以以某种方式在其中集成模板成员函数的实例化:
template<int> struct S;
#define M(I, n) \
template<> struct S<I> { \
static const char name[] = #n; \
/*
Some how instantiate the function here, like (just guessing here):
static const SEvaluator<I> eval = &C::F<I>;
given
template<int I>
using SEvaluator = void(*)();
*/
};
M(0, "foo"); M(1, "bar");
#undef M
我提出的方法无法按原样工作,并且编译器抱怨F不是constexpr。F操作的多个变量C
并调用外部方法,因此无法声明constexpr。有没有办法挽救这个问题,还是我必须求助于我的第一种骇人听闻的方法?
您可以使用index_sequence<I...>
(C ++ 14)并扩展I
到静态数组。
template<std::size_t... Is>
void G(int i, std::index_sequence<Is...>) {
using C = void(C::*)();
static C funcs[sizeof...(Is)] = { &C::F<Is>... };
(this->*funcs[i])();
}
void G(int i) {
G(i, std::make_index_sequence<256>());
}
对于非C ++ 14解决方案,您可以编写自己的版本index_sequence
:
template<int... Is>
struct index_sequence { };
template<int N, int... Is>
struct make_index_sequence : make_index_sequence<N - 1, N - 1, Is...> { };
template<int... Is>
struct make_index_sequence<0, Is...> : index_sequence<Is...> { };
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句