C ++ function map implementation

I play with variable templates in the new C ++ standard and came up with a map function (headers + using exceptions):

template<typename T>
T square(T i)
{
        return i * i;
}

template <typename T, typename... Ts>
const tuple<Ts...> map(const T f, const Ts...args)
{
        return make_tuple(f(args)...);
}

int main(int c, char *argv[])
{
        tuple<int, int> t;
        int (*fp) (int) = square;

        t = map(fp, 6, 8);

        cout <<get<0>(t) <<endl;
        cout <<get<1>(t) <<endl;

        return 0;
}

What works. So far, all arguments are of the same type for the card. If I changed the main one to use a slightly more general form:

 tuple<int, float> t;

 t = map(square, 6, 8.0f);

gcc 4.4 reports:

In function ‘int main(int, char**)’:
error: no matching function for call to ‘map(<unresolved overloaded function type>, int, float)’

Any ideas how to make this work?

+5
source share
1 answer

-, ( ), . , int (*)(int) float (*)(float). , , , .

, , std::function , , . :

template<typename T, typename Ts...>
tuple<Ts...> map(std::function<T (T)> const &f, Ts... args) {
    return make_tuple(static_cast<Ts>(f(static_cast<T>(args)))...);
}

., , ( T), ( Ts) , , .

(, , ... , ), , Ts , . , , , ... , , -, , , .

+5

All Articles