如何使可变参数模板类方法接受函数指针作为参数,从函数模板派生类型? [英] How to make variadic template class method take function pointer as argument with type derived from function template?

查看:674
本文介绍了如何使可变参数模板类方法接受函数指针作为参数,从函数模板派生类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,标题是一个口。我正在处理类似于此处讨论的数组类。我想定义一个映射函数,它接受用户定义的函数并将其应用于数组的每个元素。为了进行类型检查,我想定义它,使用户指定的函数必须使用与传递给map函数相同数量的参数,以便

Sorry the title is a mouthful. I'm working on an array class similar to the one discussed here. I want to define a "map" function that takes a user-defined function and applies it to each element of the array. For the purposes of type-checking, I'd like to define it such that the user-specified function must take the same number of arguments as are passed to the map function, so that

double f(double a, double b) { return a + b; }
Array<double,2> x, y, z; x.map(f, y, z);

将编译,但

double g(double a, double b, double c) { return a + b + c; }
Array<double,2> x, y, z;. x.map(g, y, z);

不会,因为 g

我尝试过一种语法:

template<typename T, size_t ... Ns> class Array
{
    template<class ... Args> inline const Array<T, Ns...>
        map(T (*fn)(decltype(Args, double)...), Args...)
    {
        // doesn't compile
    }
}

我认为这是接近的,但显然是错误的,因为它不编译。我非常感谢学习这样的操作的正确语法。

I think this is close, but obviously wrong, since it doesn't compile. I'd be grateful to learn the correct syntax for an operation like this.

推荐答案

template <typename T, std::size_t ... Ns>
struct Array
{
    template <typename>
    using arg_type = T;

    template <class ... Args>
    Array<T, Ns...> map(T (*fn)(arg_type<Args>...), Args...)
    {
        return {};
    }
};

DEMO

这篇关于如何使可变参数模板类方法接受函数指针作为参数,从函数模板派生类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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