0

所以,我正在为一个作业开发一个模板化的 Vector 类,我遇到了一些通过谷歌搜索解决的问题,但我仍然想知道为什么我做错了。第一个问题是我有:

template <typename T>
class Vector
{
    ...
    template <typename T2>
    Vector(const Vector<T2> &other);
}

template <typename T, T2>
Vector<T>::Vector(const Vector<T2> &other)
{
    ...
}

这给了我 VS11 中的“无法将函数定义与现有声明匹配”。我通过将模板定义放在单独的行上来修复它:

template <typename T>
template <typename T2>
Vector<T>::Vector(const Vector<T2> &other)
{
    ...
}

但我仍然不知道为什么需要这样做。我知道第一个定义对于在其中使用多个模板的函数/类是有效的,但是为什么当您将模板化类与模板化成员函数混合时语法会发生变化?

我的第二个问题与模板类中的类型有关。在编写迭代器时,我有以下功能:

template <typename T>
class Vector
{
    ...
    class iterator
    {
        ...
        iterator &operator++(void);
    }
}

template <typename T>
Vector<T>::iterator &Vector<T>::iterator::operator++(void)
{
    ...
}

这给了我“依赖名称不是类型”,后来我发现我需要在前面添加“类型名称”:

template <typename T>
typename Vector<T>::iterator &Vector<T>::iterator::operator++(void)
{
    ...
}

在谷歌搜索警告号(导致错误)之后,我意识到为什么存在错误,但编译器为什么不知道这Vector<T>::iterator是一种类型并不是很明显。我的意思是,它有类的定义,所以......

无论如何,感谢您为我澄清了这几件事!

4

1 回答 1

1
template <typename T>
template <typename T2>
Vector<T>::Vector(const Vector<T2> &other)
{

也可以写成

template <typename T> template <typename T2>
Vector<T>::Vector(const Vector<T2> &other)
{

您只需要 (?) 将其写成两组,因为它们毕竟是两组参数——第一组用于类,第二组用于函数。

typename对于依赖类型和相关规则(this对于模板基类成员和template模板成员函数(?))与称为“两阶段查找”的东西有关。然而,这在 MSVC++ 上实现得很糟糕(因为没有实现),因此它可能不会像符合标准的实现那样抛出尽可能多的错误。

更多信息 - http://blog.llvm.org/2009/12/dreaded-two-phase-name-lookup.html http://womble.decadent.org.uk/c++/template-faq.html#disambiguation http ://eli.thegreenplace.net/2012/02/06/dependent-name-lookup-for-c-templates/

于 2013-02-27T06:33:51.767 回答