简体   繁体   中英

Template function with std::map gives error: variable or field declared void

Trying to create template function what couts the std::map elements, get this errors. I know what the map have four template arguments, but two have defaut values, cant understand what I have to do.

template<typename key, typename val> void arr_out (std::map<key, val>::iterator begin, std::map<key, val>::iterator end)
{
    std::cout << "map: " << std::endl;
    while(begin != end)
    {
        std::cout << (*begin).first << ": " << (*begin).second << std::endl ;
        begin++;
    }
    std::cout << std::endl;
}
  • error: variable or field 'arr_out' declared void
  • error: expected ')' before 'begin'
  • error: expected ')' before 'begin'

You should add typename keyword before each of template function arguments:

template<typename key, typename val> 
void arr_out (typename std::map<key, val>::iterator begin, 
              typename std::map<key, val>::iterator end)

Add typename before iterator, it indicates that its nested value type of template.

template<typename key, typename val> 
void arr_out(typename std::map<key, val>::iterator begin, typename std::map<key, val>::iterator end)
{
    std::cout << "map: " << std::endl;
    while(begin != end)
    {
        std::cout << (*begin).first << ": " << (*begin).second << std::endl ;
        begin++;
    }
    std::cout << std::endl;
}

The rules of template deduction don't allow you to infer key or val from std::map<key, val>::iterator .

The other answers tell you how to correct the definition, but you have to specify the type parameters when you use it.

int main()
{
    std::map<int, std::string> m;
    // arr_out(m.begin(), m.end()); // errors relating to template argument deduction
    arr_out<int, std::string>(m.begin(), m.end()); // Ok
    return 0;
}

to make code valid, you have to add typename ,

template<typename key, typename val>
void arr_out (typename std::map<key, val>::iterator begin,
              typename std::map<key, val>::iterator end);

and as parameters are not deducible, call it:

std::map<Key, Value> m;
arr_out<Key, Value>(m.begin(), m.end());

An alternative to simplify call site is:

template <typename It>
void arr_out (It begin, It end);

or with some SFINAE:

template <typename It>
auto arr_out (It begin, It end)
-> decltype(void(std::cout << (*begin).first << (*begin).second));

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