头文件中的Lambda错误 [英] Lambda in header file error
问题描述
在我的一个课程中,我试图将std::priority queue
与指定的lambda进行比较:
In one of my classes, I am trying to use std::priority queue
with a specified lambda for comparison:
#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
文件来附加标题:
My program compiles perfectly until I add a .cpp
file to accompany the header:
#include "foo.h"
int foo::bar()
{
return 0;
}
这一次,我的编译器生成了一个错误:
This time, my compiler generates an error:
>main.obj : error LNK2005: "class <lambda> compare" (?compare@@3V<lambda>@@A) already defined in foo.obj
如果我的头文件包含lambda,为什么不能创建随附的.cpp
文件?
Why can't I create a accompanying .cpp
file if my header file contains a lambda?
编译器:Visual Studio 2012
Compiler: Visual Studio 2012
我的main.cpp
:
#include "foo.h"
int main(){
return 0;
}
推荐答案
按照@Rapptz的建议,
As @Rapptz suggested,
const auto compare = [] (const int &a, const int &b) { return a > b; };
解决了问题.为什么?
内部与外部链接.默认情况下,与int
一样,auto
具有外部链接.因此:
Internal vs External linkage. By default, auto
, like int
has external linkage. So just how:
int j = 5;
在foo.h
中随后会被foo.cpp
包含的
会抛出
In foo.h
that would later be included by foo.cpp
throws a
错误2错误LNK2005:Header.obj中已经定义了"int j"(?j @@ 3HA)
Error 2 error LNK2005: "int j" (?j@@3HA) already defined in Header.obj
(VS 2013)
但是,const
默认将链接设置为内部,这意味着该链接只能在一个翻译单元中访问,从而避免了该问题.
However, const
makes the linkage internal by default, which means it is only accessible in one translation unit, thereby avoiding the problem.
这篇关于头文件中的Lambda错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!