简体   繁体   中英

Using a template class in multiple classes in C++

Suppose I have 3 classes as shown在此处输入图像描述

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.

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;
   }
};

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