Hao Shen
Hao Shen

Reputation: 2755

In C++, how to declare a data structure in header file , while it is defined in source file?

Say I want to use typedef to define a new set MyTypeSet with customized hash and comparator functions in a source file. I want to hide all the implementation details in the source file.

typedef std::unordered_set<MyType, MyTypeHash, MyTypeKeyEqual>
MyTypeSet;

Then I want to declare MyTypeSet in header file for other modules to use. But I do not want to expose MyTypeHash and MyTypeKeyEqual

Just can not figure out the right syntax.

Upvotes: 0

Views: 408

Answers (1)

Jack C.
Jack C.

Reputation: 774

This can't be done with typedef. The user of MyTypeSet needs to be able to see complete definitions for MyType, MyTypeHash, and MyTypeKeyEqual in order to know how to compile MyTypeSet.

There are a few approaches in use to demarcate the public interface of templated code from the implementation details:

  • Put the implementation details in another header ("MyTypeImpl.hpp") that is included in the public header.
  • Put the private implementation types in a namespace named detail, private, or similar.
  • Mangle the private names with underscore characters, as in MyTypeHash_. (This can be seen a good bit in the MSVC standard library).

If it is absolutely imperative to keep MyTypeHash and MyTypeKeyEqual secret, then one could declare MyTypeSet as a class that only has the methods needed by the end user. Then MyTypeSet could use the pImpl idiom to have a std::unordered_set as a member variable visible only in the source file. All of the methods of MyTypeSet would be implemented by calling into the std::unordered_set.

Such a MyTypeSet cannot have exactly the same public interface as std::unordered_set, because std::unordered_set exposes its hash and key types as member types.

Upvotes: 2

Related Questions