Passing arithmetic function objects into map

There was this question here, asking about how to make a particular piece of code shorter: http://cplusplus.com/forum/beginner/282476/

Just for fun, I was trying to something like the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <map>
#include <functional>

int main()
{
    using FuncPtr = double *(double, double);
    
    std::map<char, FuncPtr> ops {
        { '+', std::plus<>{} },
        { '-', std::minus<>{} },
        { '*', std::multiplies<>{} },
        { '/', std::divides<>{} }
    };
    
    std::cout << ops['+'](3.0, 2.0) << '\n';
}


That is, let a map decide whether to call std::plus, std::minus, etc.
https://en.cppreference.com/w/cpp/utility/functional/plus

But I get compiler errors,
In file included from /usr/include/c++/4.9/bits/stl_algobase.h:64:0,
                 from /usr/include/c++/4.9/bits/char_traits.h:39,
                 from /usr/include/c++/4.9/ios:40,
                 from /usr/include/c++/4.9/ostream:38,
                 from /usr/include/c++/4.9/iostream:39,
                 from 1:
/usr/include/c++/4.9/bits/stl_pair.h: In instantiation of 'struct std::pair<const char, double*(double, double)>':
14:5:   required from here
/usr/include/c++/4.9/bits/stl_pair.h:102:11: error: field 'std::pair<const char, double*(double, double)>::second' invalidly declared function type
       _T2 second;                /// @c second is a copy of the second object
           ^
 In function 'int main()':
14:5: error: no matching function for call to 'std::map<char, double*(double, double)>::map(<brace-enclosed initializer list>)'
14:5: note: candidates are:
In file included from /usr/include/c++/4.9/map:61:0,
                 from 2:
/usr/include/c++/4.9/bits/stl_map.h:270:9: note: template<class _InputIterator> std::map<_Key, _Tp, _Compare, _Alloc>::map(_InputIterator, _InputIterator, const _Compare&, const allocator_type&)
         map(_InputIterator __first, _InputIterator __last,
         ^
/usr/include/c++/4.9/bits/stl_map.h:270:9: note:   template argument deduction/substitution failed:
14:5: note:   cannot convert '{'*', std::multiplies<void>{}}' (type '<brace-enclosed initializer list>') to type 'const std::less<char>&'


I tried alternative syntaxes such as using parentheses instead of {}, or not using <> or (), or using <double> instead, but no luck.

Any idea how to get something like this to work? Preferably without having to make my own struct, but it's fine if that's the only way.
Last edited on
Try
 
    using FuncPtr = std::function<double(double, double)>;

Yep, that works. Thank you.

Apparently lambdas work, too: http://www.cplusplus.com/forum/beginner/282476/#msg1222630 if one wanted to avoid std::function.
Last edited on
Topic archived. No new replies allowed.