c++ - 模板类的重载/特化方法

标签 c++ templates

我想要一个具有两个同名方法的模板化类:一个采用 T& 类型的参数,另一个采用 Rational& 作为参数,其中 Rational 是我的类。 我不确定这是否称为模板特化或只是简单的重载 另一件事是我没有 h 和 cpp 文件,而是一个包含实现声明的 hpp 文件。

正确的语法是什么?

像这样的东西:

template <class T> class Matrix
{

    bool hasTrace (Rational& trace) const
    {
    }

    bool hasTrace (T& trace) const
    {
    }
}

只有这段代码无法编译,我得到了编译错误:

..\/Matrix.hpp:200:7: error: 'bool Matrix<T>::hasTrace(T&) const [with T = Rational]' cannot be overloaded
..\/Matrix.hpp:180:7: error: with 'bool Matrix<T>::hasTrace(Rational&) const [with T = Rational]'

我现在看了这个教程: enter link description here

在模板特化下,它说我想完成的事情可以通过在类定义之外定义专门的函数来完成,同时用我希望重新定义函数的特定类型替换模板类型:

bool Matrix<Rational>::hasTrace (Rational& trace) const
{
}

但现在我得到这个错误:

..\/Matrix.hpp:227:6: error: specializing member 'Matrix<Rational>::hasTrace' requires 'template<>' syntax

再次感谢

最佳答案

如果 TRational,您需要禁用第二个重载。对于 C++,您将使用专门化:

template <class T> class Matrix
{
    bool hasTrace (Rational& trace) const
    {
    }

    bool hasTrace (T& trace) const
    {
    }
};

template<> class Matrix< Rational >
{
    bool hasTrace (Rational& trace) const
    {
    }
};

对于 C++11,您还可以使用 std::enable_if:

#include <type_traits>

template <class T> class Matrix
{
    bool hasTrace (Rational& trace) const
    {
    }

    typename std::enable_if< !std::is_same< T, Rational >::value, bool >::type
    hasTrace (T& trace) const
    {
    }
};

(或者您可以使用 Boost 的类型特征在 C++98 中实现相同的功能)

关于c++ - 模板类的重载/特化方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18724134/

相关文章:

c++ - 基类构造函数错误

c++ - 链表 const 迭代器

c++ - C++17 之前的函数交错

c++ - 在 std::function 原型(prototype)中使用 'this' 指针

c++ - Lambda 和 std::function

c++ - 在排序的 std::list 中搜索的复杂性是什么?

c++ - 未定义的类引用

templates - C++11: "parameter pack"和 "variadic template"之间有什么区别?

使用 lambda 进行 C++ 模板参数推导

c++ - 如何为其他类成员函数编写模板包装器方法?