template class restriction

前端 未结 2 1107
滥情空心
滥情空心 2021-02-09 22:15

I\'m wondering if there is any way to restrict generating code for a template using custom conditions in my case i want to function foo to be called only if template class T has

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-09 22:39

    Yes, following technique can be used (for public inheritance). It will cause an overhead of just one pointer initialization.

    Edit: Re-writing

    template
    struct IsParentChild
    {
      static Parent* Check (Child *p) { return p; }
      Parent* (*t_)(Child*);
      IsParentChild() : t_(&Check) {} // function instantiation only
    };
    
    template
    void foo ()
    {
      IsParentChild check;
    // ...
    }
    

提交回复
热议问题