CosmicCoder123
CosmicCoder123

Reputation: 31

Using a template class in multiple classes in C++

Suppose I have 3 classes as shownenter image description here

Instead of the functions in the object class I would like to create a single template function which can take the place of the two functions in the object class. The issue I am having is I do not know how to allow the template function to take arguments either of type modifier_1 or type modifier_2. Is there a way to do this?

Thank you.

Upvotes: 1

Views: 4265

Answers (1)

Isaac Clancy
Isaac Clancy

Reputation: 418

I can think of 3 solutions that might work for what you want.

1.

class object : public modifier_1, public modifier_2
{
private:
   int x{};
   template<class Modifier>
   void modify_by_modifier_helper(Modifier mod, int modifier)
   {
      x += modifier;
   }
public:
   object() = default;
   void modify_by_modifier(modifier_1 mod, int modifier)
   {
      modify_by_modifier_helper(mod, modifier);
   }

   void modify_by_modifier(modifier_2 mod, int modifier)
   {
      modify_by_modifier_helper(mod, modifier);
   }
};

2.

#include <type_traits>

class object : public modifier_1, public modifier_2
{
private:
   int x{};
public:
   object() = default;

   template<class Modifier>
   void modify_by_modifier(Modifier mod, int modifier)
   {
      static_assert(std::is_same_v<std::decay_t<Modifier>, modifier_1> ||
         std::is_same_v<std::decay_t<Modifier>, modifier_2>,
         "Modifier must be modifier_1 or modifier_2")

      x += modifier;
   }
};

3.

#include <type_traits>

class object : public modifier_1, public modifier_2
{
private:
   int x{};
public:
   object() = default;

   template<class Modifier>
   std::enable_if_t<std::is_same_v<std::decay_t<Modifier>, modifier_1> ||
         std::is_same_v<std::decay_t<Modifier>, modifier_2>, void>
   modify_by_modifier(Modifier mod, int modifier)
   {
      x += modifier;
   }
};

Upvotes: 2

Related Questions