Que*_*ble -1 c++ struct namespaces class
所以通常我不会问这样的问题,因为它似乎可能是基于意见的,或者对编码实践发起某种口头战争,但我认为这里可能有一个我不明白的技术原因。
我正在查看 vcpkg(微软正在创建的库打包管理器,是“新”代码)的头文件中的代码,因为阅读代码通常是学习您不知道的东西的好方法。
我注意到的第一件事是使用using而不是typedef。
来自“ https://github.com/microsoft/vcpkg/blob/master/toolsrc/include/vcpkg/parse.h ”的片段
template<class P>
using ParseExpected = ExpectedT<std::unique_ptr<P>, std::unique_ptr<ParseControlErrorInfo>>;
Run Code Online (Sandbox Code Playgroud)
我之前没有亲自使用过using这种方式,答案来自:What is the Difference Between 'typedef' and 'using' in C++11? 。本质上,using是一种新的实现方式,好处是可以使用模板。所以微软有充分的理由使用using而不是typedef.
看着' https://github.com/microsoft/vcpkg/blob/master/toolsrc/include/vcpkg/commands.h '我注意到他们没有使用任何类。相反,它只是其中包含函数等的名称空间。IE:
namespace vcpkg::Commands
{
namespace BuildExternal
{
void perform_and_exit(const VcpkgCmdArguments& args, const VcpkgPaths& paths, const Triplet& default_triplet);
}
}
Run Code Online (Sandbox Code Playgroud)
我猜测其中的一部分是调用语法看起来本质上就像类中的静态成员函数,因此代码执行相同的操作,但可能通过作为命名空间而不是类来节省一些开销。(如果有人对此也有任何想法,那就太好了。)
现在是这一切的要点。为什么 Microsoft 在其命名空间中使用结构而不是类?
来自“ https://github.com/microsoft/vcpkg/blob/master/toolsrc/include/vcpkg/parse.h ”的片段:
namespace vcpkg::Parse
{
/* ... Code I'm excluding for brevity ... */
struct ParagraphParser
{
ParagraphParser(RawParagraph&& fields) : fields(std::move(fields)) {}
void required_field(const std::string& fieldname, std::string& out);
std::string optional_field(const std::string& fieldname) const;
std::unique_ptr<ParseControlErrorInfo> error_info(const std::string& name) const;
private:
RawParagraph&& fields;
std::vector<std::string> missing_fields;
};
}
Run Code Online (Sandbox Code Playgroud)
搜索 stackoverflow,我发现了一个老问题:为什么 Microsoft 对 directX 库使用结构而不是类? 答案本质上是,您不必将事物声明为默认的公开内容,也不必在底部以注释方式声明它是旧代码。
如果 vcpkg 是旧代码我会完全满意,但是,这是新代码。难道他们只是继承了某种风格(但usingvstypedef不是)?还是为了节省一行代码(public:)?或者有某种间接收益吗?还是还有其他我根本没有考虑到的事情?
和之间的唯一区别是:structclass
默认成员访问权限 ( publicvs private) 和
如果从类型继承(公共继承与私有继承),则为默认继承。
一旦作者完成将public:/添加private:到类型中,最终结果 1 将是相同的。2 继承的时候可以通过显式的方式轻松控制自己,而不是依赖默认的。这没什么大不了的,也不重要。
至于为什么微软使用struct而不是class在他们的代码中,你必须问一些微软的人。