When executing the code below, you can use the function that should have been tied up in namespace as it is.
Is it a name space specification?
Depending on whether or not you are using the Vector2 structure declared in the namespace test.
The success or failure of compilation has changed.
AddVector() can't be understood to have been compiled successfully with or without Test::.
If you combine AddVector() itself by another name, such as the namespace utility {}
compiling
Util::AddVecro();//NG
Test::Util::AddVector();//OK
will be
#include<stdlib.h>
namespace Test {
structure Vector2 {
float x;
floaty;
};
floatAddFloat(floata,floatb){
return a+b;
}
Vector2AddVector(const Vector2&srcA, const Vector2&srcB){
Vector2 add;
add.x = srcA.x + srcB.x;
add.y = srcA.y + srcB.y;
return add;
}
} // namespace Test
int main(intargc, char*argv[]){
floatfloatTest[2];
floatfloatAdd1 = AddFloat(floatTest[0], floatTest[1]); // NG
floatfloatAdd2 = Test::AddFloat(floatTest[0], floatTest[1]);// OK
Test::Vector2test[2];
Test::Vector2 add;
add = AddVector(test[0], test[1]); // OK
return 0;
}
Sayuri san As you answered, Test::AddVector
is automatically found by the C++ language argument dependent name lookup (ADL).
If you want the source code in question to be a compilation error, you can explicitly prohibit ADL by combining the nested namespace with the using namespace
declaration as follows:
namespace Test {
structure Vector2 {
float x;
floaty;
};
namespace adl_barrier {
// Define a function in the nested namespace...
Vector2AddVector(const Vector2&srcA, const Vector2&srcB){
Vector2 add;
add.x = srcA.x + srcB.x;
add.y = srcA.y + srcB.y;
return add;
}
}
// ...include nesting namespace again
using namespace adl_barrier;
} // namespace Test
int main(int, char*[]){
Test::Vector2test[2];
Test::Vector2 add;
add = AddVector(test[0], test[1]); // NG!
// AddVector not found because ADL does not work
// If you explicitly modify the namespace, of course it's OK.
// add=Test::AddVector(test[0], test[1]);
}
ADL;real-argument dependent name search.
add=AddVector(test[0], test[1]);
However, the first argument test[0]
is of type Test::Vector2
, so Test::AddVector()
is searched.
As described in Wikipedia,
std::cout<<"hello, world.\n";
Even though I didn't specify a namespace, I called std::operator<<()
, so I used it without realizing it.
© 2024 OneMinuteCode. All rights reserved.