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

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

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

代码:

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 之前声明方法

是因为argument dependent lookup(ADL)。

调用 compare(first.element, second.element) 的两个参数属于 Value 类型,因此搜索 Value 的整个封闭命名空间,即全局命名空间,并重载compare 找到 Value

如果您将 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);
}