Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separating template interface and implementation in C++

This is a follow up question to: Using export keyword with templates

As mentioned in the answers of the original questions 'export' is deprecated in C++0x and rarely supported by compilers even for C++03. Given this situation, in what way can one hide actual implementations in lib files and just expose declarations through header files, So that end user can know what are the signatures of the exposed API but not have access to the source code implementing the same?

like image 350
Alok Save Avatar asked Mar 24 '11 10:03

Alok Save


People also ask

What is separation of interface and implementation?

Separating interface from implementation allows to fully use polymorphism. In this way SomeComponentV2Impl will have 3 types - own, base class, and interface. Here you may just use only the interface without caring about it's implementation in further classes.

How class interface can be separated from its implementation?

In the C language, a good way to separate interface from implementation is to put the interface in a `header file' with suffix . h , and the implementation in a file with suffix . c . Clients get access to the interface by including the header file.

Why should you strive for separation of interface from implementation?

So separating interfaces from implementations and using polymorphism makes for code that's simpler to read and understand, and that's less likely to have bugs. This is one of the strongest features of OOP.

How a class can be separated by its implementation in C++?

C++ allows developers to separate the implementation code for member functions from the class definition, but there is no comparable support for separating the member data that implements an object's state (or, for that matter, for separating the declarations of private member functions).


2 Answers

In practice you cannot.

Only if you have a certain set of specializations, you can put these in a library. The base template cannot be put there.

On the other hand, using export did not hide the source. The compiler still needed it to instantiate new classes from the template.

like image 155
Bo Persson Avatar answered Sep 17 '22 23:09

Bo Persson


In short, you can't. The export keyword was a failed attempt to achieve something akin to non-source template libraries (though not even approaching the level of obfuscation that binary code achieves), and there is no replacement in the offing.

like image 21
Marcelo Cantos Avatar answered Sep 18 '22 23:09

Marcelo Cantos