简体   繁体   中英

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;
}

How to handle situation like this to keep the main function can execute correctly? To make struct A able to use its member function.

Since it seems unable to use extern "C++" in a struct and it will report error templates must have C++ linkage currently.

dcl.link All functions and variables whose names have external linkage and all function types have a language linkage.

Class types do not. Wrapping a struct in extern "C" has no effect.

dcl.link Linkage from C++ to objects defined in other languages and to objects defined in C++ from other languages is implementation-defined and language-dependent. Only where the object layout strategies of two language implementations are similar enough can such linkage be achieved.

You should just #ifdef out C++-specific parts of your struct , such as access specifications and member functions, and hope (or find in the platform documentation) that your C compiler produces a struct with the layout identical to that produced by the C++ compiler.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM