简体   繁体   English

如何使用变量模板类方法将函数指针作为参数与从函数模板派生的类型?

[英]How to make variadic template class method take function pointer as argument with type derived from function template?

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. 我想定义一个“map”函数,它接受用户定义的函数并将其应用于数组的每个元素。 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 出于类型检查的目的,我想定义它,使得用户指定的函数必须使用与传递给map函数相同数量的参数,以便

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

will compile but 会编译但是

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

won't, becuase g takes the wrong number of arguments based on what was passed to the map function. 不会,因为g根据传递给map函数的内容获取错误数量的参数。

I've tried a syntax like: 我尝试过这样的语法:

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 DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM