Semi-generic function

Posted by Fredrik Ullner on Stack Overflow See other posts from Stack Overflow or by Fredrik Ullner
Published on 2010-03-28T20:51:25Z Indexed on 2010/03/28 21:13 UTC
Read the original article Hit count: 241

Filed under:
|
|

I have a bunch of overloaded functions that operate on certain data types such as int, double and strings. Most of these functions perform the same action, where only a specific set of data types are allowed. That means I cannot create a simple generic template function as I lose type safety (and potentially incurring a run-time problem for validation within the function).

Is it possible to create a "semi-generic compile time type safe function"? If so, how? If not, is this something that will come up in C++0x?

An (non-valid) idea;

template <typename T, restrict: int, std::string >
void foo(T bar);
...
foo((int)0); // OK
foo((std::string)"foobar"); // OK
foo((double)0.0); // Compile Error

Note: I realize I could create a class that has overloaded constructors and assignment operators and pass a variable of that class instead to the function.

© Stack Overflow or respective owner

Related posts about c++

Related posts about generics