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

允我心安 提交于 2019-12-22 08:55:32

问题


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

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.

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.


回答1:


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



来源:https://stackoverflow.com/questions/36387749/how-to-make-variadic-template-class-method-take-function-pointer-as-argument-wit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!