Re: throwable .vs. non throwable?
* Jim Langston:
I have a template I use for converting types:
template<typename T, typename F > T StrmConvert( const F from )
{
std::stringstream temp;
temp << from;
T to = T();
temp >> to;
return to;
}
template<typename F> std::string StrmConvert( const F from )
{
return StrmConvert<std::string>( from );
}
As you can see, it doesn't throw. If the conversion can not take place,
then it simply returns a default constructed type, which is fine for most
cases I use it. However, there may be a case where I want to throw on error.
I know I could simply copy this template and give it a new name, such as
StrmConvertThrow but I don't like that solution. What I would like to be
able to do (which may not be possible) is something like:
int i = 10;
std::string x;
x = StrmConvert( i ):throwable;
or such. I don't think that's right, well, okay, I know it's not right. I
do know that there is a throw( int ) type keyword for functions.
That's an exception specification. It specifies which types of
exceptions a function can throw. It doesn't cause exceptions to be thrown.
I tried to
duplicate StrmConvert like this:
template<typename T, typename F > T StrmConvert( const F from ) throw(
int )
but got compile time errors.
console5.cpp(17) : warning C4290: C++ exception specification ignored except
to indicate a function is not __declspec(nothrow)
console5.cpp(24) : error C2382: 'StrmConvert' : redefinition; different
exception specifications
console5.cpp(3) : see declaration of 'StrmConvert'
so apparently C++ doesn't distinguish between function signatures by throw
or not.
You mean, apparently it does distinguish. You forgot to place the same
throw specification on the second overload.
Although I seem to recall something about there being a new, and a
new throwable.
Am I barking up the wrong tree, or is there a way to do what I want?
Uhm, what's wrong with boost::lexical_cast?
But anyway, what you're describing is parameterizing the function with
whether it should throw or not. For that you can check the fail()
member function. If failure and should throw, then throw.
You can pass that parameter as a template parameter (decision at compile
time) or as an ordinary function argument (decision at run time). It
might seem natural to use bool for this. But I advice definining a
suitable enum type, so that the client code becomes more readable --
and that also goes for silly shorthand "Strm": vowels are cheap and
plentiful, there's no need to avoid using them! ;-)
Hope this helps,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?