Ste*_*and 26 c++ stl using std argument-dependent-lookup
在一些c ++实践中,我试图学习并采用复制交换习语,对这个问题进行彻底的解释:复制交换习语.
但我发现了一些我从未见过的代码:using std::swap; // allow ADL在这个例子中
class dumb_array
{
public:
// ...
void swap(dumb_array& pOther) // nothrow
{
using std::swap; // allow ADL /* <===== THE LINE I DONT UNDERSTAND */
swap(mSize, pOther.mSize); // with the internal members swapped,
swap(mArray, pOther.mArray); // *this and pOther are effectively swapped
}
};
Run Code Online (Sandbox Code Playgroud)
using std::swap;在函数实现的主体内部意味着什么?MSa*_*ers 61
这种机制通常用于模板化代码,即template <typename Value> class Foo.
现在的问题是使用哪个交换.std::swap<Value>会有用,但可能不太理想.有一个很好的机会,swap类型的更好的重载Value,但在哪个命名空间?它几乎肯定不在std::(因为那是非法的),但很可能在命名空间中Value.可能,但远非确定.
在这种情况下,swap(myValue, anotherValue)将为您提供"最佳"交换.Argument Dependent Lookup将在命名空间中找到任何交换Value.否则该using指令将启动,std::swap<Value>并将被实例化和使用.
在您的代码中,mSize可能是一个整数类型和mArray一个指针.它们都没有关联的命名空间,并且std::swap无论如何都具有99.9%的确定性.因此,using std::swap;这里的声明似乎毫无用处.
Ben*_*oit 11
该using关键字已范围的影响.
这意味着std::swap可以swap在using关键字的范围内引用它.
| 归档时间: |
|
| 查看次数: |
5310 次 |
| 最近记录: |