Lambda头文件错误

yiz*_*lez 9 c++ lambda

在我的一个类中,我试图使用std::priority queue指定的lambda进行比较:

#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;
};
Run Code Online (Sandbox Code Playgroud)

我的程序编译完美,直到我添加一个.cpp文件随附标题:

#include "foo.h"

int foo::bar()
{
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这次,我的编译器生成错误:

>main.obj : error LNK2005: "class <lambda> compare" (?compare@@3V<lambda>@@A) already defined in foo.obj
Run Code Online (Sandbox Code Playgroud)

.cpp如果我的头文件包含lambda,为什么我不能创建一个附带的文件?

编译器:Visual Studio 2012

我的main.cpp:

#include "foo.h"

int main(){
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

yiz*_*lez 8

正如@Rapptz建议的那样,

const auto compare = [] (const int &a, const int &b) { return a > b; };
Run Code Online (Sandbox Code Playgroud)

解决了这个问题.为什么?

内部与外部联系.默认情况下,auto就像int有外部链接一样.那么如何:

int j = 5;
Run Code Online (Sandbox Code Playgroud)

在foo.h那之后将被foo.cpp抛出a

错误2错误LNK2005:已在Header.obj中定义"int j"(?j @@ 3HA)

(VS 2013)

但是,默认情况下const将链接设置为内部,这意味着它只能在一个转换单元中访问,从而避免了问题.