0

Is there a way to specify that a template parameter type must be derived from a particular base class? This is how I wish it would work:

class  foo
{
    a_foo_function() const;
};
//.......
template  < class F : public foo >  // <<<=== my deceptively creative syntax
class bar
{
    F * pfd;
    bar(F* food){ pfd = food; }
    void f() const {  pfd->a_foo_function();  }  //guaranteed to work in my book
};
//.......
class foo                         just_a_plain_foo;
//.......
class foodish : public foo {}     a_foodish;
//.......
class foolish : public not_foo {} a_foolish;
//.......
class foodous : public foodish {} a_foodous;
//.......
typedef bar<foodish> barf;
barf a(a_foodish); //ok
barf b(a_foodous); //ok
barf c(a_foolish); //NOT ok ... foolish is not derived from foo
barf d(just_a_plain_foo); //NOT ok ... pfd pointer is to derived foodish

Ain't that beautiful? But my beautiful syntax won't compile, though; and I can't seem to find how to do this. Note that using the base class as template parameter won't work for me, as I may have distinct and mutually incompatible classes deriving from foo. TIA.

Dan
  • 1
  • 2
  • Does this answer your question? [Class to take any subclass of Base](https://stackoverflow.com/questions/49109813/class-to-take-any-subclass-of-base) – Raymond Chen Mar 31 '21 at 01:19
  • Yes, static_assert would do it; I just wasn't familiar with it. I guess I could also use a require clause; I'm just learning about concepts. Thanks. – Dan Apr 05 '21 at 18:21
  • I just wanted to add that I read that question about a dozen times and I don't understand the question at all. However, I know now the answer to my question, and that is to add a require concept is_derived. – Dan Apr 06 '21 at 20:23

0 Answers0