Reputation: 579
I’m using std::chrono
to track how much time is elapsed from the instantiation until every call to someMethod()
.
A minimal sample code looks like this:
#include <chrono>
class TestClass
{
public:
TestClass();
void someMethod();
private:
std::chrono::time_point<std::chrono::steady_clock> m_timeBegin;
};
TestClass::TestClass() :
m_timeBegin(std::chrono::steady_clock::now())
{
}
void TestClass::someMethod()
{
auto timeNow = std::chrono::steady_clock::now();
auto msSinceCreation =
std::chrono::duration_cast<std::chrono::milliseconds>(timeNow - m_timeBegin);
}
I want to get rid of the #include
in the header.
Beside compilation and link times, my main concern is about encapsulation. Using std:chrono
is only relevant in the implementation. In order to use Testclass
there is absolutely no need to use it or even know it’s involved.
Here is some possible scenario. If someone using the TestClass
decide to use std::chrono
, he can do it without add the #include
. Then, if in the future the implementation of TestClass
change stop using std:chrono
(and in consequence removing the #include
) the other code will stop compiling with no reason.
Obviously the guy who forgot to add the include did it wrong. But also obviously this will occur we like it or not.
As it is possible that it is relevant for certain solutions, SomeMethod()
is called frequently and performance is important in my scenario.
Upvotes: 2
Views: 2142
Reputation: 5569
Your problem would be solved if time_point
was a custom type, because then you could just forward declare it, change the member to a (unique) pointer, and move the include to the .cpp file. However, forward declaration of std
types is undefined behavior, so that is not possible. This leaves you basically with the following options:
std::chrono::time_point<std::chrono::steady_clock>
in a custom class. Then you can safely forward declare that type, change the member to a (unique) pointer, and move the include of the custom class (which includes <chrono>
) into the .cpp file.I understand your motivation. Still, while your scenario that someone uses <chrono>
and forgets to include it is not far fetched, it is a problem of that someone, not yours. So you should think about whether it is really necessary to introduce some complexity, just to hide the <chrono>
header. The standard library includes usually dont hurt, especially because they do not introduce rebuild impact.
As others have noted, using a smart pointer for the pimpl idiom or the forward declared type would introduce another include, namely <memory>
. Even though this is usually a more common header than <chrono>
you just exchanged one include for another. So if you really want to avoid additional includes, you may want to use a raw pointer. But then you have to take care of other problems, such as copy and move operations.
Upvotes: 6