简体   繁体   中英

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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