D编程语言中的Pimpl习惯用法 [英] Pimpl-idiom in the D programming language

查看:96
本文介绍了D编程语言中的Pimpl习惯用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

D有一个很棒的模块系统,与C ++相比,它可以大大减少编译时间.根据文档,D仍然提供不透明的结构和联合以启用pimpl习惯用法.我的问题是:如何在一个模块中声明嵌套结构(或并集),然后在另一个模块中定义它?它的语法是什么?

D has a fantastic module system which reduces compilation times dramatically compared to C++. According to the documentation D still provides opaque structs and unions in order to enable the pimpl idiom. My question is: How can I declare a nested struct (or union) in one module and define it in another one? What is the syntax for that?

在C ++中,标题看起来像这样

In C++ the header would look like this

struct S { 
    ... 
    struct Impl; 
    Impl * p; 
};

和实现文件(cpp文件)将使用一些看起来很有趣的::语法,如下所示:

and the implementation file (cpp-file) would use some interesting-looking ::-syntax like this:

#include "header.h"
struct S::Impl { 
    ... 
};

如何在D中实现相同的功能?

How do I implement the same in D?

推荐答案

D(至少为DMD)使用.di文件进行声明.它们在某种程度上等效于C .h文件,但是它们是可选的. D编译器可以自动生成.di文件(在指定-H开关时),尽管我认为当前所做的只是剥离功能主体和单元测试.

D (DMD, at least) uses .di files for declarations. They are somewhat equivalent to C .h files, however they are optional. The D compiler can generate .di files automatically (when the -H switch is specified), although I believe that currently all it does is strip function bodies and unittests.

这是使用.di文件实现PImpl的一种方法:

Here's one way to achieve PImpl using .di files:

  • mod.di:

struct S
{
    struct I;
    I* pi;
}

  • mod.d:

    struct S
    {
        struct I
        {
            int v;
        }
    
        I* pi;
    }
    

  • 请注意,目前您有责任确保.d.di文件中的S中的字段相同-如果它们不同,则编译后的模块将对这些字段的知识有所不同布局会导致内存损坏.当前的编译器实现无法验证.d.di文件中的定义是否匹配.

    Note that it is currently your responsibility to make sure that the fields in S are the same in both the .d and .di file - if they differ, the compiled modules will have differing knowledge of how the fields are laid out, which can lead to memory corruption. The current compiler implementations do not verify if definitions match in .d and .di files.

    这篇关于D编程语言中的Pimpl习惯用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆