[英]How does a templated class resolve an overloaded non-member function called on one of its types?
In the following example, I've created a mock Container class for an arbitrary type.在以下示例中,我为任意类型创建了一个模拟 Container 类。 Calling compare() on the Container calls compare() for the Value object stored inside.
在 Container 上调用 compare() 会为存储在其中的 Value 对象调用 compare()。 How is the compare() function overloaded for Value resolved in
Container<Value>
when it is declared afterwards and is not a member function of Value?当之后声明并且不是 Value 的成员函数时,如何在
Container<Value>
解析为 Value 重载的 compare() 函数?
Code:代码:
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;
}
Output (as expected):输出(如预期):
0
-1
模板只有在实例化时才会得到解析,因此您的compare
Value
方法只需要在main
之前而不是在compare
Container
方法之前声明
It is because the argument dependent lookup (ADL).这是因为参数依赖查找(ADL)。
The two arguments of the call compare(first.element, second.element)
are of type Value
, so the whole enclosing namespace of Value
, ie, the global namespace, is searched, and the overload of compare
for Value
is found.通话的两个参数
compare(first.element, second.element)
是类型的Value
,所以全封闭命名空间Value
,即全局命名空间,搜索,和的过载compare
的Value
发现。
If you replace Value
by a fundamental type, eg int
, then there is no ADL and the code won't work:如果您将
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.