Can we have absolute namespace in function definition if return type is an object in C++?

点点圈 提交于 2019-12-01 09:28:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!