【发布时间】:2015-02-19 21:09:13
【问题描述】:
我发现了类似的问题Lambda expressions as class template parameters 和How to use a lambda expression as a template parameter?,但即使有可用的答案,我也不明白为什么以下代码不起作用(g++4.8.2 和 g++-4.9):
auto GoLess = [](int a,int b) -> bool
{
return a < b;
};
template<typename Order>
struct foo
{
int val;
bool operator<(const foo& other)
{
return Order(val, other.val);
}
};
typedef foo<decltype(GoLess)> foo_t;
int main()
{
foo_t a,b;
bool r = a < b;
}
编译器输出为:
test.cpp: In instantiation of ‘bool foo<Order>::operator<(const foo<Order>&) [with Order = <lambda(int, int)>]’:
test.cpp:26:15: required from here
test.cpp:17:30: error: no matching function for call to ‘<lambda(int, int)>::__lambda0(int&, const int&)’
return Order(val, other.val);
^
test.cpp:17:30: note: candidates are:
test.cpp:5:16: note: constexpr<lambda(int, int)>::<lambda>(const<lambda(int, int)>&)
auto GoLess = [](int a,int b) -> bool
^
test.cpp:5:16: note: candidate expects 1 argument, 2 provided
test.cpp:5:16: note: constexpr<lambda(int, int)>::<lambda>(<lambda(int, int)>&&)
test.cpp:5:16: note: candidate expects 1 argument, 2 provided
这段代码不应该工作吗?从我理解的其他线程中读取此代码应该编译,但不是。
非常感谢
附录:
为了澄清一点,在上述问题中,KennyTM 编写了以下代码:
auto comp = [](const A& lhs, const A& rhs) -> bool { return lhs.x < rhs.x; };
auto SetOfA = std::set <A, decltype(comp)> (comp);
哪个应该起作用,std::set 的第二个参数是一个“比较器”,在这种情况下是一个 lambda,在我的代码中我正在尝试做同样的事情,或者至少我认为我在做同样的事情,但我的代码不起作用。我的代码中缺少什么?
请注意 Xeo 在Lambda expressions as class template parameters
auto my_comp = [](const std::string& left, const std::string& right) -> bool {
// whatever
}
typedef std::unordered_map<
std::string,
std::string,
std::hash<std::string>,
decltype(my_comp)
> map_type;
这应该也可以。我的错在哪里?
谢谢
【问题讨论】:
-
请解释为什么您认为代码应该编译。 (这可能会影响答案。)
-
const。检查您的consts。
标签: c++ templates c++11 lambda