Reputation: 5856
I am trying to understand the concept of type traits.
Say i have some templatized Class Hierachy like this and a client function:
template<typename T>
class Base
{
public:
//...
virtual bool inline isSymmetric() const = 0;
};
template<typename T>
class ChildrenOperation : public Base<T>
{
public:
//...
virtual bool inline isSymmetric() const override
{
return true;
}
};
template<typename T>
void clientFunction(const Base<T>& operation)
{
//...
if(operation.isSymmetric())
{
// use operation in one way
} else {
// use operation in another way
}
}
Obviously, clientFunction is polymorphic and different children can have different implementations of isSymmetric. However, since isSymmetric seems to be constant and really more of a type information, i've read about type traits and i was wondering whether it is possible to rewrite the client function to not depend on isSymmetric on runtime, but rather compile time.
I've tried adding a trait like this. But i am not sure how to specialize it and use it in a polymorphic context.
template <typename T>
struct is_symmetric {
static const bool value = false;
};
Upvotes: 0
Views: 424
Reputation: 11720
If being symmetric depends on the concrete type derived from Base
, then you cannot use a type traits for this situation. Type traits are evaluated in compile time, so if you have a polymorphic type which's traits are not known at compile time, then you cannot use type traits.
One possible solution, if the symmetricity is really constant, is this:
class Base {
public:
Base(bool symmetric) : symmetric(symmetric) {}
bool isSymmetric() {
return symmetric;
}
// ...
private:
bool symmetric;
};
class ChildrenOperation : public Base {
public:
ChildrenOperation() : Base(true) {}
// ...
};
I did not use the templates here because they are irrelevant in this case. Of course, if symmetricity depends on T then you can use type traits, like this:
template <typename T>
struct is_symmetric : public std::false_type {};
template <>
struct is_symmetric<SymmetricT> : public std::true_type {};
So the solution depends on whether the trait depends only on the dynamic type of the object, in which case you should use the fist code, the template parameter, in which case you should use the second code, or both. From your example, it's not entirely clear which is your situation.
Upvotes: 1