【问题标题】:use the signature of a generic function dependent on a non-type template argument as template template argument使用依赖于非类型模板参数的泛型函数的签名作为模板模板参数
【发布时间】:2017-12-15 15:43:14
【问题描述】:

下面的小程序可以编译和运行,它允许将unsigned 类型的运行时变量index 与一组具有J 类型unsigned 的模板参数的模板函数桥接。

如果需要进一步澄清,请在this question 中进行更好的解释。

我编写的辅助函数使用模板模板参数,从原始函数中推断出尽可能多的信息。问题是我找不到更好的方法来定义模板模板参数FunWrap,而不是创建2个包装器wrap_foowrap_zoo,而我希望直接用作模板模板参数foozoo。有没有办法做到这一点?

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

【问题讨论】:

    标签: templates c++14 template-templates


    【解决方案1】:

    我希望直接将foozoo 用作模板模板参数。有没有办法做到这一点?

    由于foozoo 是模板函数,恐怕答案是否定的。 C++ 在处理重载集/模板方面是出了名的糟糕。示例:Disambiguate overloaded member function pointer being passed as template parameter

    【讨论】:

      猜你喜欢
      • 2014-06-07
      • 2018-05-01
      • 1970-01-01
      • 2010-12-17
      • 1970-01-01
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 2019-04-24
      相关资源
      最近更新 更多