C++ symbol mangling and exporting => Allow code duplication?
In our project we have something like this:
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 proposed to change that into something like that:
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 that was refused and I was told: "There 开发者_StackOverflow中文版is one problem with this approach - C++ symbol mangling and exporting. Templates are so long when used in exported symbols (API that uses them) and there is no way how to export templates."
Is that argument so strong to allow lot of code duplication?
Your boss (or whatever) is probably right. If you write a library that should be usable from other languages than C++, it is generally a good idea to write the interface in C only.
Of course, you can still internally use templates, just don't expose them.
there is no way how to export templates
This is only true for C linkage (i.e. if you use extern "C" when exporting). There's no technical problem exporting a template class out of a shared library -- just think of the STL classes exported from the C++ runtime library.
It's true that due to CPP's name mangling not being standardized, the client of your exported class will have to use the same compiler you do (and often the same compiler version) -- but this may be acceptable in closed environments. BTW, this is the reason you often have to install Microsoft's Visual C++ 200X Redistributable packages before installing new software. MS redistributable packages solve this problem specifically for the CPP runtime libraries on Windows platforms.
There are methods for exporting templates, if you're using Visual Studio, you can check out __declspec(dllimport/dllexport)
, which is very powerful. I don't know if other compilers offer this. However, if you don't export a C-compatible interface, then you're basically forcing the user to use the same compiler as you, at least the same vendor, if not the same exact model.
精彩评论