简体   繁体   中英

How do I separate test types with the template extern keywords?

Suppose I have some type X which is templated on T :

// hpp file
template <typename T>
struct X
{
  int Get();
};

extern template X<TraitsType>;

// cpp file
template <typename T>
int X<T>::Get() { return T::Get(); }

template X<TraitsType>;

The type T might be a random number generator in a production environment ( TraitsType ), but for the sake of unit tests it might be a type that will generate predictable or fudgible values (say, TestTraitsType ). If I want to use this TestTraitsType I now have to scatter extern template and template declarations for X<TestTraitsType> throughout my hpp and cpp files, which is undesirable because I am polluting my production code with unit test code.

How can I avoid this while keeping these type instantiations in separate translation units?

Move method definitions in (private) header .inl (or .hxx )

  •  // inl file template <typename T> int X<T>::Get() { return T::Get(); } 
  •  // cpp file #include "X.inl" template X<TraitsType>; 
  •  // test file #include "X.inl" template X<TestTraitsType>; 

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