簡體   English   中英

Lambda頭文件錯誤

[英]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; };

解決了這個問題。 為什么?

內部與外部聯系 默認情況下, autoint一樣具有外部鏈接。 那么如何:

int j = 5;

在后來被foo.cpp包含的foo.h中會拋出一個

錯誤2錯誤LNK2005:已在Header.obj中定義“int j”(?j @@ 3HA)

(VS 2013)

但是, const默認情況下將鏈接設置為內部 ,這意味着它只能在一個轉換單元中訪問,從而避免了問題。

由於某種原因,我無法復制此問題。 我在VS2010上嘗試這個 - 不確定這是否有所作為。 事實上,我嘗試將您的標題包含在兩個源文件中,它編譯,鏈接和運行正常。

那就是說,你想考慮使用std::function 這樣你就可以在cpp代碼中定義lambda,並且不會出於任何原因多次定義它。 (順便說foo.objfoo.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM