Alok Save
Alok Save

Reputation: 206546

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?

Upvotes: 10

Views: 3616

Answers (4)

Klaim
Klaim

Reputation: 69682

You can use extern template in most recent compilers : http://en.wikipedia.org/wiki/C%2B%2B0x#Extern_template

However, it's unperfect as it only limit template instantiation. The idea is that you separate the template declaration and implementation in two seperate files.

Then when you need the template, you use extern template first, to make sure it's not instantiated yet. Then for each instantiation you need ( one for std::vector, one for std::vector, etc) , put the instantiation in a typedef that will be in a unique cpp.

As it makes the code clearly harder to understand, it's not the best solution yet. But it does works : it helps minimize template instantiations.

Upvotes: 1

Matthieu M.
Matthieu M.

Reputation: 299920

One thing I have often noticed is that a good chunk of template code, is not so template in fact, and can be moved to non-template functions.

It also happens that function template specialization are considered as regular functions: you can either define them inline (and mark them so) or declare them in a header and implement them in a source file.

Of course, specialization means that you know with which type it will be executed...

Note that what you are asking for is somewhat antithetic.

The very goal of template is to create a "pattern" so that the compiler can generate classes and functions for a multitude of unrelated types. If you hide this pattern, how do you expect the compiler to be able to generate those classes and functions ?

Upvotes: 1

Marcelo Cantos
Marcelo Cantos

Reputation: 185862

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.

Upvotes: 2

Bo Persson
Bo Persson

Reputation: 92271

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.

Upvotes: 8

Related Questions