prasadrahul
prasadrahul

Reputation: 105

Have different behavior for specific type in a template function

I am working on a logHelper function. I have overloaded the << operator and I write the value to a ostream objecct. How do I handle the case for specialized behavior for classes derived from the same base class.

To be more specific, I want to add string returned by what() for an exception.

template <class T> 
    LogStream& operator<<(const T& t)
    {
        if (std::is_base_of<std::exception, T>::value)
        {
            std::exception exception = std::dynamic_cast<std::exception>(t);
            m_output << exception.what();
        }
        else
        {
            m_output << t;
        }
        return *this;
    }

Upvotes: 2

Views: 899

Answers (1)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153820

If you want to have different code depending on the template argument, you need to somehow provide entirely separate definition chosen at an opportune point in type. For example, you could use

template <class T> 
typename std::enable_if<std::is_base_of<std::exception, T>::value, LogStream>::type&
operator<<(const T& t)
{
    m_output << t.what();
    return *this;
}

template <class T> 
typename std::enable_if<!std::is_base_of<std::exception, T>::value, LogStream>::type&
operator<<(const T& t)
{
    m_output << t;
    return *this;
}

Using std::enable_if<condition, T> with negated conditions should enable one or the other implementation.

Upvotes: 3

Related Questions