简体   繁体   中英

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?

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.

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.

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM