gpt4 book ai didi

c++ - 在 std::for_each 中使用 std::bind

转载 作者:行者123 更新时间:2023-11-28 05:43:03 25 4
gpt4 key购买 nike

考虑以下片段:

#include <string>
#include <map>
#include <memory>
#include <utility>
#include <iostream>

typedef std::string::size_type StrSize;

//Strips the passed symbol from the start and end of the passed source string.
void Strip(std::string& source, const char* symbol)
{
StrSize v_start = source.find_first_not_of(symbol);
source.erase(0, v_start);

StrSize v_end = source.find_last_not_of(symbol);
if (v_end < (source.size() - 1))
{
source.erase(v_end + 1);
}
}

///Strips the symbol from the start and end of all strings in the container.
template <class T>
void Strip(T& source, const char* symbol)
{
for_each(source.begin(), source.end(), std::bind(Strip, std::placeholders::_1, symbol));
}

编译使用:

g++ -g -std=c++11 -c <filename>.cpp

它会产生以下错误:

testBInd.cpp: In function ‘void Strip(T&, const char*)’:
testBInd.cpp:26:90: error: no matching function for call to ‘bind(<unresolved overloaded function type>, const std::_Placeholder<1>&, const char*&)’
for_each(source.begin(), source.end(), std::bind(Strip, std::placeholders::_1, symbol));
^
testBInd.cpp:26:90: note: candidates are:
In file included from /usr/include/c++/4.8.2/memory:79:0,
from testBInd.cpp:3:
/usr/include/c++/4.8.2/functional:1655:5: note: template<class _Func, class ... _BoundArgs> typename std::_Bind_helper<std::__or_<std::is_integral<typename std::decay<_Tp>::type>, std::is_enum<typename std::decay<_Tp>::type> >::value, _Func, _BoundArgs ...>::type std::bind(_Func&&, _BoundArgs&& ...)
bind(_Func&& __f, _BoundArgs&&... __args)
^
/usr/include/c++/4.8.2/functional:1655:5: note: template argument deduction/substitution failed:
testBInd.cpp:26:90: note: couldn't deduce template parameter ‘_Func’
for_each(source.begin(), source.end(), std::bind(Strip, std::placeholders::_1, symbol));
^
In file included from /usr/include/c++/4.8.2/memory:79:0,
from testBInd.cpp:3:
/usr/include/c++/4.8.2/functional:1682:5: note: template<class _Result, class _Func, class ... _BoundArgs> typename std::_Bindres_helper<_Result, _Func, _BoundArgs>::type std::bind(_Func&&, _BoundArgs&& ...)
bind(_Func&& __f, _BoundArgs&&... __args)
^
/usr/include/c++/4.8.2/functional:1682:5: note: template argument deduction/substitution failed:
testBInd.cpp:26:90: note: couldn't deduce template parameter ‘_Result’
for_each(source.begin(), source.end(), std::bind(Strip, std::placeholders::_1, symbol));

你能解释一下我哪里错了吗?为什么找不到匹配的调用?

最佳答案

编译器不能决定使用哪个重载函数,如果你只指定名称,可能的修复:

std::for_each(source.begin(), source.end(), std::bind(
static_cast<void (*)(std::string&, const char *)>(Strip),
std::placeholders::_1, symbol));

关于c++ - 在 std::for_each 中使用 std::bind,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36737935/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com