我在命名空间 N 中有一个类 C,它有一个公共(public)模板成员函数 F,如下所示:
namespace N {
class C {
public:
template<int I>
void F() {
// ...
}
};
};
I
的值对于 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。有没有办法挽救这个问题,还是我必须求助于我的第一个 hackish 方法?
最佳答案
您可以使用 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...> { };
关于c++ - 强制模板成员函数实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33976949/