gpt4 book ai didi

c++ - 在 C++ 头文件中放置 using 指令的位置

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:09:22 25 4
gpt4 key购买 nike

对于我的项目,我使用了一些非常复杂的数据结构,例如

std::unordered_map<int, std::list<std::shared_ptr<const Foo>>>

为了可读性,我想为其声明类型别名。我构建项目的代码已经通过在头文件中全局放置 using 语句来做到这一点:

// bar.h
#ifndef BAR_H
#define BAR_H

#include <unordered_map>
#include <list>
#include <memory>
#include "foo.h"

using FooTable = std::unordered_map<int, std::list<std::shared_ptr<const Foo>>>;

class Bar {
FooTable create_foo();
};

#endif

因为我的 C++ 知识有点生疏,所以我只是采用了这种风格——但现在我读到以这种方式使用 using 可能会有问题,因为它会在所有包含它的东西上强制使用这个别名标题。

尽管进行了大量的谷歌搜索,但我找不到关于如何正确处理这个问题的具体答案,只有很多关于不该做什么的声明。所以,我只是将 using 放在类中:

// bar.h
#ifndef BAR_H
#define BAR_H

#include <unordered_map>
#include <list>
#include <memory>
#include "foo.h"


class Bar {
using FooTable = std::unordered_map<int, std::list<std::shared_ptr<const Foo>>>;

FooTable create_foo();
};

#endif

但是这有一个缺点,我需要在源文件中重申别名:

// bar.cpp
#include "bar.h"

using FooTable = std::unordered_map<int, std::list<std::shared_ptr<const Foo>>>;

FooTable Bar::create_foo()
{
...
}

虽然这似乎有效,但我不确定这是否安全……我的直觉告诉我它有点丑陋。所以在我像这样重写我的整个项目之前,我想我会问:是否有更好/更优雅/更安全的方法来做到这一点?还是我应该完全避免在头文件中使用类型别名?

最佳答案

However this has the drawback, that I need to restate the alias in the source file:

这是不正确的。您只需要将它设置为 public 然后指定适当的范围,这样您就可以在 Bar 的范围之外调用它 Bar::FooTable (其中包括返回类型,除非尾随!):

Bar::FooTable Bar::create_foo()
{ /* ... */ }

auto Bar::create_foo() -> FooTable
{ /* ... */ }

(只是 FooTable 很好定义中,因为它是成员!)

您的方法很好,但我也会将所有内容都放在命名空间中。那么您的别名是否在类中并不重要:它仍然独立于您自己的代码中。这纯粹是一种风格问题,对其他人几乎没有影响。

关于c++ - 在 C++ 头文件中放置 using 指令的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57756881/

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