Eh, function templates are compiled at compile time.Quote:
Once I found out template using function actually compile on run-time, it scared me away from them for good.
Printable View
Eh, function templates are compiled at compile time.Quote:
Once I found out template using function actually compile on run-time, it scared me away from them for good.
Hmm, I was about to point you to that page that said that, but after reading it again, I realized it didn't!
Just because you can't see the alternate solution doesn't mean it isn't there. If 50% of the code is the same, then that 50% should be broken out into another function, so that only the changing 50% is written in the specializations.
RTTI is a crutch. It often indicates poor programming.
Overloading would still be better here, I think. For example, like this:
Code:#include <boost/mpl/bool.hpp>
template <typename E,
typename T,
typename A,
typename N>
void StringToNumHelper( const std::basic_string<E, T, A>& str,
N& num, boost::bool_<true> )
{
// Signed implementation.
}
template <typename E,
typename T,
typename A,
typename N>
void StringToNumHelper( const std::basic_string<E, T, A>& str,
N& num, boost::bool_<false> )
{
// Unsigned implementation.
}
template <typename E,
typename T,
typename A,
typename N>
void StringToNum( const std::basic_string<E, T, A>& str,
N& num )
{
StringToNumHelper( str, num,
boost::bool_<std::numeric_limits<N>::is_signed>() );
}
Actually, the StringToNumHelper() implementation is exactly the same for signed & unsigned. The only difference is the signedness of the N type; and since I don't like to copy and paste code for no reason, I did it like that.
I also could have overloaded StringToNum() for each signed & unsigned integer type, but I just felt like condensing it into 1 function.
If the implementation is the same, why have two functions at all?
Maybe... if I ever get the time to learn about all those cool Boost libraries.
Because I need to pass either a long or unsigned long to the helper function to do it's job correctly here's the helper function:
I was getting compile errors for everything I did if I tried to combine them into one function.Code:template <typename E,
typename T,
typename A,
typename LN, // long or unsigned long.
typename N>
void
StringToNumHelper( const std::basic_string<E, T, A>& str,
LN& lnum,
N& num )
{
std::basic_stringstream<E, T, A> ss( str );
if ( !(ss >> lnum) || (lnum < std::numeric_limits<N>::min()) || (lnum > std::numeric_limits<N>::max()) )
{
throw std::invalid_argument( "Error converting string to number!" );
}
num = static_cast<N>( lnum );
}
i was in a similar position once.
the solution i used was to create different derived classes for each type with virtual getters and setters.
I get it - you need a larger type to avoid overflow.
Not hard to solve with a simple metafunction, though. Boost might even have such a thing. But then, Boost also has lexical_cast.