使用依赖于非类型模板参数的泛型函数的签名作为模板模板参数 [英] use the signature of a generic function dependent on a non-type template argument as template template argument

查看:96
本文介绍了使用依赖于非类型模板参数的泛型函数的签名作为模板模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我编写的辅助函数使用模板模板参数,以从原始函数中推断出尽可能多的信息.问题是,除了创建两个包装器wrap_foowrap_zoo之外,我找不到定义模板模板参数FunWrap的更好方法,而我想直接将foozoo.有办法吗?

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

推荐答案

我想直接将foozoo用作模板模板参数.有办法吗?

I would have liked to use as template template argument directly foo and zoo. Is there a way to do that?

由于foozoo是模板函数,因此恐怕答案是否定的.众所周知,C ++在处理重载集/模板方面很糟糕.示例:将歧义重载的成员函数指针作为模板参数传递

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

这篇关于使用依赖于非类型模板参数的泛型函数的签名作为模板模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆