AndyX
AndyX

Reputation: 101

Splitting class definition into multiple module units in C++

Is there any way to split class definition (implementation) into more than one module unit? It can be helpful in case if one or more class's methods are big enough to be placed in separate source files. The best solution I see could be class declaration in module interface file and one of its methods definition in separate module implementation file. But it doesn't work because compiler doesn't see class declaration compiling module implementation file:

//module interface unit
export module test;
export class foo
{
   void f();
};

//module implementation unit
module test;
void foo::f() {} // compiler doesn't know about foo class and its methods

Upvotes: 7

Views: 2888

Answers (3)

AndyX
AndyX

Reputation: 101

Big thanks to everyone answering my question. The example published in my initial question works. As I wrote in one of my answers to Davis Herring (thank you, Davis, for correcting class method's name in my example) the problem was in my compiling environment. There is absolutely no need to use module partitions to solve this issue - they are for different purposes (for example, for dealing with libraries).

Upvotes: 3

bitnick
bitnick

Reputation: 2073

Module.ixx

export module foolib;
export import :foo;
export import :fooimpl;
export import :fooimpl2;

foo.ixx

export module foolib:foo;
export class foo
{
public:
    void hello1();
    void hello2();
};

fooimpl1.ixx

export module foolib:fooimpl;
import :foo;
void foo::hello1() {}

fooimpl2.ixx

export module foolib:fooimpl2;
import :foo;
void foo::hello2() {}

Upvotes: 5

JDługosz
JDługosz

Reputation: 5642

I think you are asking about module partitions. A single module can be split up into more than one source file by making each one separate module, but those submodules are recognised as such and put back together into a single named module automatically.

The syntax of a partition is a colon and the subname.

module foo:part1;

You can read more about it here: https://vector-of-bool.github.io/2019/03/10/modules-1.html

Just like with C++ headers, there is no requirement that modules be split and subdivided into multiple files. Nevertheless, large source files can become intractable, so C++ modules also have a way to subdivide a single module into distinct translation units that are merged together to form the total module. These subdivisions are known as partitions.

Upvotes: 0

Related Questions