简体   繁体   中英

C++ generic classes - separating interface and implementation

A very common coding practice is to separate the interface of a class from the implementation of its member functions through the use of .h and .cpp files on a per-class basis. So class Foo would be realised with a Foo.h header file and a corresponding Foo.cpp file.

This is often thrown out of the window in the special case of generic classes and instead header-only libraries are used to keep the compiler happy even though it does clutter the interface file with implementation details.

I've recently come accross some code written as follows. The .h file contains the interface and a #include to a .hpp file which contains the implementation of the generic member functions.

eg for a simple container of type T Value.h

#ifndef VALUE_H
#define VALUE_H

template <typename T>
class Value
{
public:
    Value(T value);
    void set(T value);
    T get() const;
private:
    T data;
};

#include "Value.hpp"

#endif

and the corresponding Value.hpp

#ifndef VALUE_HPP
#define VALUE_HPP

template <typename T>
Value<T>::Value(T value) : data(value)
{
}

template <typename T>
void Value<T>::set(T value)
{
    data = value;
}

template <typename T>
T Value<T>::get() const
{
    return data;
}

#endif

This has the advantage of better separating interface and implementation coupled with the further benefit of actually compiling (in my limited testing).

My question is then are there any hidden pit-falls with adopting this convention ?

Since you need to include both "value.h" and "value.hpp" in every file that uses the Value class, there is no benefit in compile time. But if you mean "it compiles" vs a solution where you put the implementation in a .cpp file, then yes, there is a benefit.

There is of course a benefit in that you can easily see the interface(s) provided by the class, without having the file cluttered up with a bunch of implementation code.

I'm not sure the naming convention of "value.h" and "value.hpp" is the 'best' choice. I think the "value.inl" is a better name for the second file.

No there are no special pitfalls with this solution. The .hpp file is just another header file which contains the definitions for the methods declared by the templated class. Since methods of templated classes needs to be defined in the header file this is a convenient method for separating the declaration from the definition. The extension .hpp shows that it is a hybrid of header and implementation file and is commonly used.

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