问题
Let us consider a function bar
declared in namespace foo
which returns a std::vector< float >
(but also works with other objects).
// header.h
#include <vector>
namespace foo
{
::std::vector< float > bar();
}
Compiling its definition using relative namespace works.
#include "header.h"
::std::vector< float > foo::bar()
{
}
However, compiling its definition using absolute namespace does not work.
#include "header.h"
::std::vector< float > ::foo::bar()
{
}
Return error from GCC is
function.cpp:3:26: error: ‘foo’ in ‘class std::vector<float>’ does not name a type
::std::vector< float > ::foo::bar()
It turns out that spaces are allowed in namespacing, so, ::std::vector< float > ::foo::bar()
is equivalent to ::std::vector< float >::foo::bar()
. How can I use absolute namespace in function definition when return type is an object?
回答1:
::std::vector< float > (::foo::bar)()
{
// stuff
}
回答2:
One way to resolve the problem is to use trailing return type.
auto ::foo::bar() -> ::std::vector< float >
{
...
}
来源:https://stackoverflow.com/questions/51427468/can-we-have-absolute-namespace-in-function-definition-if-return-type-is-an-objec