如何传递运算符作为默认函子参数?
为简单起见,假设我想实现一个函数,该函数采用两个参数和谓词来测试相等性,
template<typename T, typename TCompare>
bool Eq(const T& a, const T& b, const TCompare& cmp) {
return cmp(a, b);
}
但我还希望如果未传递谓词,则假定 operator==
。
我尝试了几种不同的方法,但都导致语法错误或“operator==”未定义。我什至尝试用 a 替换 Eq
函数
不过,我想我想要的是可能的,因为 STL 的大部分支持不传递可选的 TCompare 参数(std::sort、std::set .. .)。
更新: 感谢 levis501 的建议,这是迄今为止我发现的最好方法:
template<typename T, typename TCompare>
bool Eq(const T& a, const T& b, const TCompare& cmp) {
return cmp(a, b); // or some lengthy code
}
template<typename T>
bool Eq(const T& a, const T& b) {
static std::equal_to<T> EqCmp;
return Eq(a, b, EqCmp);
}
因此,您基本上需要创建一个传递 std::equal_to 或任何其他运算符等效函子的包装器。由于某种原因,当您调用没有它的函数时,将其作为默认参数将无法编译。
For simplicity, let's say I want to do implement a function which takes two parameters and predicate which test for equality,
template<typename T, typename TCompare>
bool Eq(const T& a, const T& b, const TCompare& cmp) {
return cmp(a, b);
}
but I also want that operator==
is assumed if predicate is not passed.
I tried several different approaches, but all resulted in either syntax error or "operator==" not defined. I even tried replacing the Eq
function with a
Nevertheless, I suppose what I want is possible since the big part of STL supports not passing the optional TCompare parameter (std::sort, std::set ...).
UPDATE:
Thanks to levis501 suggestion, this is the best way I have found so far:
template<typename T, typename TCompare>
bool Eq(const T& a, const T& b, const TCompare& cmp) {
return cmp(a, b); // or some lengthy code
}
template<typename T>
bool Eq(const T& a, const T& b) {
static std::equal_to<T> EqCmp;
return Eq(a, b, EqCmp);
}
So, you basically need to create a wrapper which passes std::equal_to, or any other operator-equivalent functor. For some reason, having it as a default argument does not compile when you invoke the function without it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
std::equal_to 怎么样? http://www.cplusplus.com/reference/std/function/equal_to/
How about std::equal_to ? http://www.cplusplus.com/reference/std/functional/equal_to/
你可以重载函数,不是吗?
如果代码使用三个参数调用
Eq()
,编译器将解析对第一个重载的调用。如果代码仅使用两个参数调用Eq()
,则编译器将必须解析第二个重载。You can overload functions, no?
If the code calls
Eq()
with three arguments, the compiler will resolve the call to the first overload. If the code callsEq()
with only two arguments, then the compiler will have to resolve to the second overload.我不认为像下面这样的东西适合你:
Default template parameters are only allowed on class templates (或者至少 MSVC 10 是这么说的)
I don't suppose something like the following would work for you:
Default template parameters are only allowed on class templates (or at least that's what MSVC 10 says)