1

How can I specify template parameter to be of a certain type i-e it must have implemented an interface (the template parameter must be a derived class of a specific base class)

Heres the interface (abstract base class)

class baseActionCounter{
public:
virtual int eat()=0;
virtual int drink()=0;
};

Now I want my template parameter to be of type baseActionCounter

Heres the templated class

//imaginary template syntax in the line below. Is there a way of achieving this behavior?
template <class counterType : baseActionCounter>

    class bigBoss{
    counterType counter;
    public:
    int consumerStats(){
    //I am able to call member function because I know that counter object has eat() and drink() 
    //because it implemented baseActionCounter abstract class
    return counter.eat() + counter.drink(); 
    }
    };

I can also just derive my bigBoss class from baseActionCounter but I want to know how to achieve this behavior with templates. Also, template specialization is not suitable as there is just one BigBoss class for any implementor of baseActionCounter class.

bsobaid
  • 955
  • 1
  • 16
  • 36

1 Answers1

2

Yes, you can use std::is_base_of to check the type, e.g.

template <class counterType, std::enable_if_t<std::is_base_of_v<baseActionCounter, counterType>>* = nullptr>
class bigBoss {

Or

template <class counterType>
class bigBoss {
    static_assert(std::is_base_of_v<baseActionCounter, counterType>, "counterType must derive from baseActionCounter");
    ...
};

Or use concept (since C++20).

template <class T>
concept Derived = std::is_base_of_v<baseActionCounter, T>;

template <Derived counterType>
class bigBoss {

BTW: std::is_base_of also returns true if the base class baseActionCounter is specified; if that's not what you want you can combine the condition with std::is_same.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • that was easy. I will try it to see if I can directly can member function of baseActionCounter. @songyuanyao, may I know how did you learn templates? I want to know enough to do these basic logical programming tasks. Material I find usually go into details of argument deductions which is just too complicated. – bsobaid Sep 02 '20 at 04:02
  • @bsobaid I learned templates from the book *C++ Templates: The Complete Guide*, you might want to check the [book list](https://stackoverflow.com/q/388242/3309790). And cppreference.com is nice for learning too. – songyuanyao Sep 02 '20 at 04:11