Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 对模板函数中的特定类型具有不同的行为_C++_Templates - Fatal编程技术网

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

C++ 对模板函数中的特定类型具有不同的行为,c++,templates,C++,Templates,我正在处理一个logHelper函数。我重载了如果您希望根据模板参数使用不同的代码,您需要以某种方式提供在适当的类型点选择的完全独立的定义。例如,您可以使用 template <class T> typename std::enable_if<std::is_base_of<std::exception, T>::value, LogStream>::type& operator<<(const T& t) { m_out

我正在处理一个logHelper函数。我重载了如果您希望根据模板参数使用不同的代码,您需要以某种方式提供在适当的类型点选择的完全独立的定义。例如,您可以使用

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;
}
模板
typename std::enable_if::type&
操作人员

使用
std::enable_if
和否定条件应启用一个或另一个实现。

您可能需要搜索“多态性”.@H2CO3:除了多态性在这里没有真正的帮助,除非你找到了一种方法来纠正重载
std::exception
的输出操作符,遵守规则重载操作符,前提是它们至少涉及一个用户定义的类型。@DietmarKühl我不懂。OP希望根据对象是否派生自某个基类来执行不同的操作。当然,你可以写一个if or或一个交换的情况,但那是C而不是C++。这种代码重用要求在面向对象语言中使用多态性。句法是次要的;通过适当的重构,这很容易做到。@H2CO3:好吧,所寻求的切换是一般性的,而不是使用[dynamic]多态性:如果某个类型属性为true,则使用一个实现,否则使用另一个实现。由于无法控制所涉及的类型,因此使用任何基于面向对象的方法都是行不通的。面向对象的部分是本例中的特定类型属性。它确实有效。现在我知道std::enable_if check。
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;
}