Lets consider the following class which checks if the type provided is a string and uses type traits to call a different function based on the result. The original source has type dependencies on Obj, this is a simplified example:
template <typename Obj>
class example {
public:
template <bool IdIsString = std::is_same<std::string, Obj>::value>
typename std::enable_if<IdIsString, void>::type
doStuff() {
this->object->doSomething();
}
template <bool IdIsString = std::is_same<std::string, Obj>::value>
typename std::enable_if<!IdIsString, void>::type
doStuff() {
this->object->doSomethingElse();
}
private:
AnyObject object;
};
How would I go about decoupling the definition (e.g. storing it in a example_inline.hpp) from the class without providing each type trait case in the definition?
An ideal solution would look like this:
// header.hpp
template <typename Obj>
class example {
public:
void doStuff();
}
// header_inline.hpp
template <typename Obj>
template <bool IdIsString = std::is_same<std::string, Obj>::value>
typename std::enable_if<IdIsString, void>::type
example::doStuff() {
// ...
}
// ...
The above is obviously not possible. One solution would be to decouple the type_trait function from the class and put it into a detail namespace but this would mean that I would have to always pass AnyObject (and in that sense, all objects that are modified by the function) to it which seems not very elegant.
Is there a good solution for this problem? I'd really like for the headers in question be easily readable without cluttering them with tons of enable_if's.
Thanks for any input on the matter.