Home Auto deduce type of function in template
Reply: 0

Auto deduce type of function in template

user1068
1#
user1068 Published in April 25, 2018, 6:04 pm

I have simple map implementation and simple id (identity):

template <typename T>
T map(const T& x, std::function<decltype(x[0])(decltype(x[0]))> f) {
    T res(x.size());
    auto res_iter = begin(res);
    for (auto i(begin(x)); i < end(x); ++i) {
        *res_iter++ = f(*i);
    }
    return res;
}

template <typename T>
T id(T& x) {return x;}

and when I call is as

vector<int> a = {1,2,3,4,5,6,7,8,9};
map(a, id<const int>);

it works, but I want call it without type specification, like this:

map(a, id);

and when I do it, I get error:

error: cannot resolve overloaded function 'id' based on conversion to type 'std::function<const int&(const int&)>'
 map(a, id);
          ^

How can I resolve it and why can't compiler deduce type of id from its context in map when error contains right bounded type?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.303796 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO