[英]Lambda in header file error
在我的一个类中,我试图使用带有指定lambda的std::priority queue
进行比较:
#pragma once
#include <queue>
#include <vector>
auto compare = [] (const int &a, const int &b) { return a > b; };
class foo
{
public:
foo() { };
~foo() { };
int bar();
private:
std::priority_queue< int, std::vector<int>, decltype(compare)> pq;
};
我的程序编译完美,直到我添加一个.cpp
文件来附加标题:
#include "foo.h"
int foo::bar()
{
return 0;
}
这次,我的编译器生成错误:
>main.obj : error LNK2005: "class <lambda> compare" (?compare@@3V<lambda>@@A) already defined in foo.obj
如果我的头文件包含lambda,为什么我不能创建一个附带的.cpp
文件?
编译器:Visual Studio 2012
我的main.cpp
:
#include "foo.h"
int main(){
return 0;
}
正如@Rapptz建议的那样,
const auto compare = [] (const int &a, const int &b) { return a > b; };
解决了这个问题。 为什么?
内部与外部联系 。 默认情况下, auto
与int
一样具有外部链接。 那么如何:
int j = 5;
在后来被foo.cpp
包含的foo.h
中会抛出一个
错误2错误LNK2005:已在Header.obj中定义“int j”(?j @@ 3HA)
(VS 2013)
但是, const
默认情况下将链接设置为内部 ,这意味着它只能在一个转换单元中访问,从而避免了问题。
由于某种原因,我无法复制此问题。 我在VS2010上尝试这个 - 不确定这是否有所作为。 事实上,我尝试将您的标题包含在两个源文件中,它编译,链接和运行正常。
那就是说,你想考虑使用std::function
。 这样你就可以在cpp代码中定义lambda,并且不会出于任何原因多次定义它。 (顺便说foo.obj
, foo.obj
来自哪里?你有另一个包含这个标题的源文件吗?)。
foo.h中:
#pragma once
#include <queue>
#include <vector>
#include <functional>
typedef std::function<bool (int, int) > comptype;
//auto compare = [] (const int &a, const int &b) { return a > b; };
class foo
{
public:
foo() { };
~foo() { };
int bar();
private:
std::priority_queue< int, std::vector<int>, comptype> pq;
};
然后在cpp中包含并定义lambda,当你创建pq
将它传递给构造函数。
Foo.cpp中:
auto compare = [] (const int &a, const int &b) { return a > b; };
foo::foo():pq(compare){}
这样你就不能多次定义函数了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.