2017-12-15 35 views
2

컴파일 및 실행되는 아래의 작은 프로그램은 런타임 변수 index을 하나의 템플릿 함수 세트와 연결합니다 템플릿 인수 Junsigned입니다.비 형식 템플릿 인수에 종속적 인 일반 함수의 서명을 템플릿 템플릿 인수로 사용

더 자세한 설명이 필요한 경우 this question에서 더 자세히 설명됩니다.

내가 작성한 보조 함수는 템플릿 함수를 사용하여 가능한 한 많은 정보를 원래 함수에서 추론합니다. 문제는 템플릿 템플릿 인수로 직접 foozoo을 사용하는 것이 좋겠지 만 wrap_foowrap_zoo 템플릿을 만드는 대신에 템플릿 템플릿 인수 FunWrap을 정의하는 것이 더 좋은 방법은 찾을 수 없다는 것입니다. 그렇게 할 수있는 방법이 있습니까?

#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; 
} 

답변