对于模板函数中的特定类型,具有不同的行为

Have different behavior for specific type in a template function

本文关键字:类型 函数 于模板      更新时间:2023-10-16

我正在开发一个logHelper函数。我已经使<lt;运算符和我将该值写入一个ostream objecct。如何处理从同一基类派生的类的特殊行为。

更具体地说,我想为一个异常添加what()返回的字符串。

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;
    }

如果您希望根据模板参数有不同的代码,您需要以某种方式提供在适当的类型点选择的完全独立的定义。例如,您可以使用

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;
}

使用具有否定条件的std::enable_if<condition, T>应该启用一个或另一个实现。