簡體   English   中英

在 extern "C" 中使用帶有模板的 extern "C++"

[英]use extern "C++" with template inside extern "C"

#include <string>
#include <sstream>
#include <iostream>

extern "C" {

struct A {
public:
#ifdef __cplusplus
    //extern "C++" {
    template<typename T>
    T to_string(T value) {
        return value;
    }

    //}
#endif /* __cplusplus */
};
}
int main() {
    A a;
    std::cout << a.to_string<int>(1);
    return 0;
}

如何處理這種情況以保持主要功能可以正確執行? 使結構 A 能夠使用其成員函數。

由於它似乎無法在結構中使用extern "C++"並且它會報告錯誤templates must have C++ linkage

dcl.link名稱具有外部鏈接且所有函數類型具有語言鏈接的所有函數和變量。

類類型沒有。 extern "C"中包裝struct無效。

dcl.link從 C++ 到用其他語言定義的對象以及從其他語言到用 C++ 定義的對象的鏈接是實現定義和語言相關的。 只有在兩種語言實現的對象布局策略足夠相似的情況下,才能實現這種聯動。

您應該只#ifdefstruct的 C++ 特定部分,例如訪問規范和成員函數,並希望(或在平台文檔中找到)您的 C 編譯器生成的結構與 C++ 編譯器生成的布局相同.

struct A {
#ifdef __cplusplus
  public:
    template<typename T>
    T to_string(T value) {
        return value;
    }
#endif /* __cplusplus */
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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