简体   繁体   中英

c++ boost lambda cout <<

Can anyone explain why this doesn't work:

std::for_each(v.begin(), v.end(), std::cout << _1 << std::endl);

while the following works fine:

std::for_each(v.begin(), v.end(), std::cout << _1 << '\n');

Assuming you have the following error, or something similar:

error C2914: 'boost::lambda::operator <<' : cannot deduce template argument as function argument is ambiguous

std::endl is in fact an unary function template of the following signature:

template <class charT, class traits>
basic_ostream<charT,traits>& endl (basic_ostream<charT,traits>& os);

Which means that when you type << std::endl then in fact you request for the function's address. In case the function is overloaded/templated, the compiler can't tell which one you want unless it can be deduced based on the parameter's type. Since the lambda operator<< is a function template as well, there is no such possibility.

To work around that, you need to manually disambiguate the call using eg static_cast :

std::for_each(v.begin(), v.end(),
              std::cout << boost::lambda::_1
                        << static_cast<std::ostream&(*)(std::ostream&)>(std::endl));

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