Search code examples
c++templatestypename

how to print template typename in c++?


I am writing a wrapper for boost numeric_cast with the wrapper function something like:

#include <boost/numeric/conversion/cast.hpp>
#include <stdexcept>

template <typename Source, typename Target>
Target numeric_cast(Source src)
{
    try
    {
        // calling boost numeric_cast here
    }
    catch(boost::numeric::bad_numeric_cast& e)
    {
        throw std::runtime_error("numeric_cast failed, fromType: " + Source + " toType: " + Target);
    }
}

I am having this error:

error: expected primary-expression before ‘(’ token
  throw std::runtime_error("numeric_cast failed ...
                          ^

I think the error is asking to handle Source and Target in the error message. So is there a way to print template typename? I am a beginner in c++, so it maybe a silly question...


Solution

  • You can use typeid(T).name() to get the raw string of the template parameter:

    #include <boost/numeric/conversion/cast.hpp>
    #include <stdexcept>
    #include <typeinfo>
    
    template <typename Source, typename Target>
    Target numeric_cast(Source src)
    {
        try
        {
            // calling boost numeric_cast here
        }
        catch(boost::numeric::bad_numeric_cast& e)
        {
            throw (std::string("numeric_cast failed, fromType: ") + 
                   typeid(Source).name() + " toType: " + typeid(Target).name());
        }
    }
    

    Demo.

    Please note that the string literal "numeric_cast failed, fromType:" should be std::string type to support '+' operator.