Sign in to follow this  
godecho

exceptions and implicit conversions

Recommended Posts

godecho    235

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

template <typename CharType>
class Foo
{
    public:

        operator       basic_string<CharType>()       { return "foo"; }
        operator const basic_string<CharType>() const { return "foo"; }
};

int main(int argc, char** argv)
{
    try
    {
        throw Foo<char>();
    }
    catch(const string& str)
    {
        cout << str << endl;
    }

    return 1;

};



The execution of this code results in an unhandled exception. Why is the implicit conversion not working for the catch clause?

Share this post


Link to post
Share on other sites
Nitage    1107
Because that's the way C++ exceptions work.

catch(const std::string&){...} will only catch exceptions of type std::string, or exceptions of a type publically derived from std::string.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this