Reputation: 1
#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.
Upvotes: 0
Views: 790
Reputation: 119867
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 */
};
Upvotes: 1