是否可以在本地匿名函数中使用来自周围模板函数的模板类型参数?我敢肯定,我不能申报模板拉姆达...如何在lambda中使用模板类型参数?
例如,我怎么会去这样做这样的事情:
template <typename T>
void TrimString(std::basic_string<T>& str, const std::locale& loc = std::locale())
{
// std::isspace as lambda unary predicate?
auto fn = [&loc](T c){ return std::use_facet<std::ctype<T>>(loc).is(std::ctype_base::space, c); };
// trim right
str.erase(std::find_if(str.rbegin(), str.rend(), std::not1(fn)).base(), str.end());
// trim left
str.erase(str.begin(), std::find_if(str.begin(), str.end(), std::not1(fn)));
}
目前这个生成以下错误:
error C2039: 'argument_type' : is not a member of '`anonymous-namespace'::<lambda0>'
这是有道理的,因为拉姆达没有关于来自周围模板函数的参数T
的线索。
我使用VS2010和gcc 4.7,但我不想使用提升。
任何想法?
编辑:看来我错了,我认为问题是模板参数本身。相反,它是使用lambda函数编译的std::not1
。以下是更详细的错误输出:
error C2039: 'argument_type' : is not a member of '`anonymous-namespace'::<lambda0>'
: see declaration of '`anonymous-namespace'::<lambda0>'
: see reference to class template instantiation 'std::unary_negate<_Fn1>' being compiled
with
[
_Fn1=`anonymous-namespace'::<lambda0>
]
: see reference to function template instantiation 'void TrimString<char>(std::basic_string<_Elem,_Traits,_Ax> &,const std::locale &)' being compiled
with
[
_Elem=char,
_Traits=std::char_traits<char>,
_Ax=std::allocator<char>
]
如果它是函数类型,是否需要显式声明参数的类型?我不知道我做错了还是......
答案:
选项1:如果我不使用std::not1
,而是否定在lambda返回值我得到相同行为没有问题。
auto fn = [&loc](T c){ return !std::use_facet<std::ctype<T>>(loc).is(std::ctype_base::space, c); };
选项2:由于拉姆达是不再等同于如何std::isspace
会表现为一个一元谓词函数对象构造演员还做的伎俩。
str.erase(std::find_if(str.rbegin(), str.rend(), std::not1(std::function<bool(T)>(fn))).base(), str.end());
顺便说一句,错误消息似乎表明问题在于其他地方,特别是在* namespace * scope声明的lambda。 – Nawaz
像这样'std :: not1(std :: function(fn))'铸造'fn'也可以。 –