【问题标题】:Can we have absolute namespace in function definition if return type is an object in C++?如果返回类型是 C++ 中的对象,我们可以在函数定义中使用绝对命名空间吗?
【发布时间】:2018-07-19 16:14:30
【问题描述】:

让我们考虑一个在命名空间foo 中声明的函数bar,它返回一个std::vector< float >(但也适用于其他对象)。

// header.h
#include <vector>

namespace foo
{
        ::std::vector< float > bar();
}

使用相对命名空间编译其定义是可行的。

#include "header.h"

::std::vector< float > foo::bar()
{
}

但是,使用绝对命名空间编译它的定义是行不通的。

#include "header.h"

::std::vector< float > ::foo::bar()
{
}

来自 GCC 的返回错误是

function.cpp:3:26: error: ‘foo’ in ‘class std::vector<float>’ does not name a type
::std::vector< float > ::foo::bar()

原来命名空间中允许有空格,所以::std::vector&lt; float &gt; ::foo::bar() 等价于::std::vector&lt; float &gt;::foo::bar()。返回类型为对象时,如何在函数定义中使用绝对命名空间?

【问题讨论】:

  • ::std::vector&lt; float &gt; ::foo::bar() 被视为::std::vector&lt; float &gt;::foo::bar()。空白被忽略。
  • auto ::foo::bar() -&gt; ::std::vector&lt; float &gt; { ... }
  • 不错,我没想到。
  • @n.m.,该评论值得提升为答案。

标签: c++ object namespaces return declaration


【解决方案1】:
::std::vector< float > (::foo::bar)()
{
    // stuff
}

【讨论】:

  • 谢谢!我没想到我们可以那样写。
  • 看起来很难看。最好将返回类型粘贴在右侧以通过那个丑陋的解析。
【解决方案2】:

解决问题的一种方法是使用尾随返回类型。

auto ::foo::bar() -> ::std::vector< float >
{
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-22
    • 2018-06-06
    • 2019-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多