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

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

本文关键字:调用 重载 函数 成员 何解析 类型      更新时间:2023-10-16

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

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

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

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

模板只有在实例化时才会被解析,因此您的compareValue方法只需要在compareContainer方法之前main而不是之前声明