Let's say:
- Some header
h.hpp
defines a template functionf()
usingsizeof
on its template parameter. - Two different C++ source files,
a.cpp
andb.cpp
, define their own structure having the same nameS
. - Both
a.cpp
andb.cpp
usef()
with their ownS
.
In other words:
h.hpp
:
template <typename T>
int f()
{
return something + sizeof(T);
}
a.cpp
:
#include "h.hpp"
struct S {
int a;
int b;
};
int aFunc()
{
return f<S>();
}
b.cpp
:
#include "h.hpp"
struct S {
int w;
int x;
int y;
int z;
};
int bFunc()
{
return f<S>();
}
Here, within the same program, both aFunc()
and bFunc()
return the same value. This is because both structures are named S
, and only one template function instantiation is kept.
My working solutions so far are:
- Name the structures differently.
- Make
f()
static
. - Make
f()
part of an anonymous namespace. - Make both structures part of their own anonymous namespace.
Can you think of anything else to avoid this issue which only manifests at run time?