在我的一个类(class)中,我尝试使用具有指定 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; };
问题解决了。为什么?
Internal vs External linkage .默认情况下,auto
与 int
一样具有外部链接。那么如何:
int j = 5;
在稍后将被包含在 foo.cpp
中的 foo.h
中抛出一个
Error 2 error LNK2005: "int j" (?j@@3HA) already defined in Header.obj
(对比 2013)
但是,const
默认使链接内部,这意味着它只能在一个翻译单元中访问,从而避免了这个问题。
关于c++ - 头文件中的 Lambda 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18113164/