c++ - 头文件中的 Lambda 错误

标签 c++ lambda

在我的一个类(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 .默认情况下,autoint 一样具有外部链接。那么如何:

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/

相关文章:

java - 在java lambda中编辑局部变量

java - 我可以在 Java 中的 lambda 表达式中放置 if 语句吗?

c++ - 执行跳过 getline()

c++ - GetDlgItemInt 和 SetDlgItemInt 的问题

c++ - gcc/clang 在基本结构的后填充中布置派生结构的字段

python - AWS lambda 在 python 中构建外部依赖库

python - 当字典的键匹配时如何从列中提取字符串

c++ - 有序双链表

c++ - OpenCV c++ HoughLines 转换不起作用

java - 如何将 TimerTask 与 lambda 一起使用?