C ++ symbol mangling and exporting => Allow code duplication?

There is something like this in our project:

struct PointI { // methods for getting, setting and calculating some point stuff private: int x; int y; }; struct PointD { // methods for getting, setting and calculating some point stuff private: double x; double y; }; 

I suggested changing this to something like this:

 template<typename T> struct Point { // methods for gettig, setting and calculating some point stuff private: T x; T y; }; typedef Point<int> PointI; typedef Point<double> PointD; typedef Point<float> PointF; 

But it was refused, and they told me: "There is one problem with this approach - changing and exporting characters in C ++. Templates are so long when used in exported characters (APIs that use them), and there is no way to export templates."

Is this argument so strong as to allow a lot of code duplication?

+4
source share
3 answers

Your boss (or something else) is probably right. If you are writing a library that should be used from languages ​​other than C ++, it is usually recommended to write the interface only in C.

Of course, you can still use templates inside, just don't expose them.

+4
source

no way to export templates

This is true only for C communication (i.e. when using extern "C" when exporting). There is no technical problem of exporting a template class from a shared library - just think of STL classes exported from the C ++ runtime library.

It is true that due to the non-standardization of the CPP name, the client of your exported class will have to use the same compiler (and often the same version of the compiler), but this may be acceptable in closed environments. By the way, this is the reason why you often have to install Microsoft Visual C ++ 200X redistributable packages before installing new software. Redistributable MS packages solve this problem specifically for CPP runtime libraries on Windows platforms.

+1
source

There are methods for exporting templates, if you use Visual Studio, you can check __declspec(dllimport/dllexport) , which is very powerful. I do not know if other compilers offer. However, if you do not export a C-compatible interface, you basically force the user to use the same compiler as you, at least the same provider, if not the exact model.

0
source

All Articles