【发布时间】:2018-12-28 12:39:48
【问题描述】:
在我的项目中,我用尽了boost-variant。因此,对于我的单元测试,我需要根据特定 T 和特定内容 t 检查变体的内容。
因此,我为此设计了函数 cmpVariant,并从我的单元测试中消除混乱。
在某些情况下,T 类型没有配备operator==,因此用户可能会传递一个满足EqualityCompare 要求的函数 (https://en.cppreference.com/w/cpp/named_req/EqualityComparable)
现在由于某些不明原因,以下代码无法编译。它说,没有匹配的功能?
Clang 6.0.1 编译器错误
prog.cc:22:5: error: no matching function for call to 'cmpVariant'
cmpVariant(number, 3.2, lambdaEquiv); // Fails!
^~~~~~~~~~
prog.cc:6:6: note: candidate template ignored: could not match 'function<bool (const type-parameter-0-1 &, const type-parameter-0-1 &)>' against '(lambda at prog.cc:19:24)'
bool cmpVariant(
^
1 error generated.
有人知道为什么吗?
代码
#include <iostream>
#include <boost/variant.hpp>
#include <functional>
template<typename V, typename T>
bool cmpVariant(
const V& variant,
const T& t,
const std::function<bool(const T& u, const T& v)>& equiv = [](const T& u, const T& v) {return u == v; })
{
if (variant.type() != typeid(t)) return false;
auto v = boost::get<T>(variant);
return equiv(v, t);
}
int main(int, char**) {
boost::variant<double, int> number{ 3.2 };
cmpVariant(number, 3.2);
auto lambdaEquiv = [](const double& x, const double& y) { return x == y; };
std::function<bool(const double&, const double&)> equiv = lambdaEquiv;
cmpVariant(number, 3.2, equiv); // Works!
cmpVariant(number, 3.2, lambdaEquiv); // Fails!
}
【问题讨论】:
-
你应该在这里发布错误信息。
-
@VTT:不幸的是,错误消息是德语,很难翻译。也许包含实时代码更合适?
-
@Aleph0 你在使用 MSVC 吗?您也可以安装英语语言包以获取英语消息,如果需要暂时切换到(或永久,我总是认为英语错误消息优于德语等价物......)。
-
@Aconcagua:我会试试,但需要一段时间。
-
即使有错误ID也比没有好。
标签: c++ templates boost-variant equality-operator