繁体   English   中英

模板化类如何解析在其类型之一上调用的重载非成员函数?

[英]How does a templated class resolve an overloaded non-member function called on one of its types?

在以下示例中,我为任意类型创建了一个模拟 Container 类。 在 Container 上调用 compare() 会为存储在其中的 Value 对象调用 compare()。 当之后声明并且不是 Value 的成员函数时,如何在Container<Value>解析为 Value 重载的 compare() 函数?

代码:

template<typename T>
class Container
{
public:
    Container(T value) : element(value) {}
    T element;
};

template<typename T>
int compare(Container<T> const& first, Container<T> const& second)
{
    return compare(first.element, second.element);
}

class Value
{
public:
    Value(int value) : value(value) {}
    int value;
};

int compare(Value const& first, Value const& second)
{
    if (first.value < second.value)
        return -1;
    else if (first.value > second.value)
        return 1;
    return 0;
}

int main()
{
    auto l1 = Container<Value>(1);
    auto l2 = Container<Value>(1);
    auto l3 = Container<Value>(2);

    cout << compare(l1, l2) << endl;
    cout << compare(l1, l3) << endl;
}

输出(如预期):

0
-1

模板只有在实例化时才会得到解析,因此您的compare Value方法只需要在main之前而不是在compare Container方法之前声明

这是因为参数依赖查找(ADL)。

通话的两个参数compare(first.element, second.element)是类型的Value ,所以全封闭命名空间Value ,即全局命名空间,搜索,和的过载compareValue发现。

如果您将Value替换为基本类型,例如int ,则没有 ADL 并且代码将不起作用:

template<typename T>
class Container
{
public:
    Container(T value) : element(value) {}
    T element;
};

template<typename T>
int compare(Container<T> const& first, Container<T> const& second)
{
    return compare(first.element, second.element); // error: no matching function for call to 'compare(const int&, const int&)'
}

int compare(int first, int second)
{
    if (first < second)
        return -1;
    else if (first > second)
        return 1;
    return 0;
}

int main()
{
    auto l1 = Container<int>(1);
    auto l2 = Container<int>(2);

    compare(l1, l2);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM