gpt4 book ai didi

c++ - 代码片段不能在 C++17 下编译,命名空间问题?

转载 作者:行者123 更新时间:2023-12-04 16:59:04 27 4
gpt4 key购买 nike

#include <iostream>
#include <vector>

namespace Cactus
{
namespace Json
{
class Value
{
public:
Value(){}

};

}

typedef std::vector< int > vectorInt;

inline Cactus::Json::Value& operator << (Cactus::Json::Value& os, const vectorInt& v)
{
return os;
}
inline Cactus::Json::Value& operator >> (Cactus::Json::Value& is, vectorInt& v)
{
return is;
}
}

namespace App
//namespace Cactus
{

void f()
{
Cactus::vectorInt ints;
Cactus::Json::Value val;

val << ints;
}
}

int main()
{
App::f();
}

遇到错误,
main.cpp: In function 'void App::f()':
main.cpp:38:13: error: no match for 'operator<<' (operand types are 'Cactus::Json::Value' and 'Cactus::vectorInt' {aka 'std::vector<int>'})
38 | val << ints;
| ~~~ ^~ ~~~~
| | |
| | Cactus::vectorInt {aka std::vector<int>}
| Cactus::Json::Value
但是如果使用“命名空间仙人掌”,它会编译。但我必须使用“命名空间应用程序”,有什么建议吗?
更新:问题已解决。
将两个操作符移动到全局命名空间的工作。
或者使用 Cactus 也可以添加。

最佳答案

它被称为 ADL .至少,在您的示例中,函数 Cactus::Json::Value& operator << (Cactus::Json::Value& os, const vectorInt& v)在参数类型的关联类或命名空间中找不到 val .因为ADL应遵守以下规则:

For each argument type T in the function call, there is a set of zero or more associated namespaces and a set of zero or more associated classes to be considered. The sets of namespaces and classes are determined entirely by the types of the function arguments (and the namespace of any template template argument). Typedef names and using-declarations used to specify the types do not contribute to this set. The sets of namespaces and classes are determined in the following way:

If T is a class type (including unions), its associated classes are: the class itself; the class of which it is a member, if any; and its direct and indirect base classes. Its associated namespaces are the innermost enclosing namespaces of its associated classes. [...]



If an associated namespace is an inline namespace, its enclosing namespace is also included in the set. If an associated namespace directly contains inline namespaces, those inline namespaces are also included in the set.


因此,类 Value 的最内层封闭命名空间是 Json .在 Value范围内,其中没有这样的可用函数,命名空间 Json 也类似。 ,因此您遇到了该错误。

如何解决?
  • 将您提供的所有函数移至命名空间 Json .
  • 修改 namespace Jsoninline namespace Json .

  • 取其中之一就好了。

    关于c++ - 代码片段不能在 C++17 下编译,命名空间问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64495276/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com