问题
The small program below, which compiles and runs, allows to bridge a runtime variable index
of type unsigned
with a set of template functions having one template argument J
of type unsigned
.
In case further clarifications are needed, this is better explained in this question.
The auxiliary functions I wrote use a template template argument, to infer as much info as possible from the original function. The problem is that I could not find a better way to define the template template argument FunWrap
other than creating the 2 wrappers wrap_foo
and wrap_zoo
, whereas I would have liked to use as template template argument directly foo
and zoo
. Is there a way to do that?
#include <iostream>
#include <utility>
#include <array>
using namespace std;
// boiler plate stuff
template <template <unsigned J> typename FunWrap, unsigned... Is>
decltype(auto) get_fun_ptr_aux(std::integer_sequence<unsigned, Is...>, unsigned i)
{
typedef decltype(&FunWrap<1>::run) FunPtr;
constexpr static std::array<FunPtr, sizeof...(Is)> fun_ptrs = { &FunWrap<Is>::run... };
return fun_ptrs[i];
}
template <template <unsigned J> typename FunWrap, unsigned N>
decltype(auto) get_fun_ptr(unsigned i)
{
return get_fun_ptr_aux<FunWrap>(std::make_integer_sequence<unsigned, N>{}, i);
}
// template functions to be bridged with runtime arguments
// two functions with same template arguments but different signature
template <unsigned J>
void foo() { cout << J << "\n"; }
template <unsigned J>
double zoo(double x) { return x + J; }
// 1 wrapper per each function
template <unsigned J>
struct wrap_foo {
static void *run() { foo<J>(); } // same signature as foo
};
template <unsigned J>
struct wrap_zoo {
static double run(double x) { return zoo<J>(x); } // same signature as zoo
};
int main()
{
unsigned index = 5;
(*get_fun_ptr<wrap_foo,10>(index))();
cout << (*get_fun_ptr<wrap_zoo,10>(index))(3.5) << "\n";
return 0;
}
回答1:
I would have liked to use as template template argument directly
foo
andzoo
. Is there a way to do that?
As foo
and zoo
are template functions, I'm afraid the answer is no. C++ is notoriously bad at dealing with overload sets/templates. Example: Disambiguate overloaded member function pointer being passed as template parameter
来源:https://stackoverflow.com/questions/47835596/use-the-signature-of-a-generic-function-dependent-on-a-non-type-template-argumen