模板化类如何解析在其类型之一上调用的重载非成员函数?
How does a templated class resolve an overloaded non-member function called on one of its types?
在下面的示例中,我为任意类型创建了一个模拟容器类。在容器上调用 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);
}
模板只有在实例化时才会被解析,因此您的compare
Value
方法只需要在compare
Container
方法之前main
而不是之前声明
相关文章:
- 调用重载的"<大括号括起来的初始值设定项列表>"对于对来说就足够了是模棱两可的
- 为什么初始化时没有调用重载赋值运算符?
- 使用 MINGW gcc 编译时,不会为 std::string 调用重载的新运算符
- 为什么使用不匹配的参数调用重载函数仍然有效
- 无法弄清楚为什么没有调用重载运算符 []
- 使用 nullptr 调用重载方法是不明确的
- C++编译时检查是否可以用某种类型的参数调用重载函数
- 在 if 语句中调用重载构造函数失败
- 为什么在析构函数中引发异常时不调用重载删除
- 从派生类调用重载函数
- 传递 const int* 和 int* 时调用重载函数的不同版本(const int* const&/&&)
- C++ - 在 std::thread 中调用重载函数时编译失败
- 为在与类方法中的类相同的命名空间中定义的结构调用重载运算符
- 从 C++ 中的子类调用重载父类的方法
- 在C++中,如何从父类变量的子类调用重载方法
- 使用指针调用重载而不分配新内存
- 如何在复制构造函数中调用重载的下标
- DetectMultiScale在使用rejectLevels和levelWeights调用重载时从不返回
- 从对象指针调用重载运算符 ()
- C++ 从类中调用重载运算符