コンパイルして実行する以下の小さなプログラムは、タイプのランタイム変数index
を1つのテンプレート関数のセットテンプレート引数J
はunsigned
です。テンプレートテンプレートの引数として非タイプのテンプレート引数に依存する汎用関数のシグネチャを使用テンプレート
さらに詳しい説明が必要な場合は、this questionで詳しく説明しています。
私が書いた補助関数は、元の関数から可能な限り多くの情報を推測するためにテンプレートテンプレート引数を使用します。問題は、2つのラッパーwrap_foo
とwrap_zoo
を作成する以外のテンプレートテンプレート引数FunWrap
を定義する良い方法を見つけることができなかったのに対し、テンプレートテンプレート引数として直接foo
とzoo
を使用したかったです。それを行う方法はありますか?
#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;
}