Re: Using templates to build a type-safe interface to existing code
Michael Le Barbier Gr?newald <michipili@googlemail.com> wrote in
news:95b77bff-2678-41dd-b918-9a95572f9c55@googlegroups.com:
Dear Group,
I would like to write a new, type-safe, interface to existing code. I
wonder if it is possible to define a template and specialisation of
this template such that use of the non-specialised template triggers
an error at compile time (good) or link time (worse).
I figured out I need this to solve my interface problem, it may worth
to describe it in greater details, maybe you habe an even better
solution!
Existing-code is a printing facility, built around an enum, like
enum STYLE { DOUBLE1, DOUBLE2, STRING1, STRING2 }
and overloaded functions
void print(STYLE, double);
void print(STYLE, const& string);
The first parameter of the print function is used to convey styling
information and, as the name suggests, DOUBLE1 and DOUBLE2 are only
soundly used in conjunction with a double while STRING1 and STRING2
should be used with strings (std::string).
As far as I see you just want to get a compile-time error when print(...,
double) is not called with DOUBLE1 or DOUBLE2. Then maybe something like
that:
enum STYLE { DOUBLE1, DOUBLE2, STRING1, STRING2 };
template<STYLE style>
void print(double) {
static_assert(style==DOUBLE1 || style==DOUBLE2,
"Invalid style parameter!");
// ...
}
int main() {
print<DOUBLE1>(3.14);
print<STRING1>(6.28);
}
This produces (with MSVC2010):
ClCompile:
test.cpp
test.cpp(7): error C2338: Invalid style parameter!
test.cpp(17) : see reference to function template instantiation
'void print<STRING1>(double)' being compiled
Build FAILED.
Use BOOST_STATIC_ASSERT or whatever if your compiler does not support
static_assert() yet.
hth
Paavo