template class restriction

前端 未结 2 1066
滥情空心
滥情空心 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<typename Parent, typename Child>
    struct IsParentChild
    {
      static Parent* Check (Child *p) { return p; }
      Parent* (*t_)(Child*);
      IsParentChild() : t_(&Check) {} // function instantiation only
    };
    
    template<typename T>
    void foo ()
    {
      IsParentChild<Bar, T> check;
    // ...
    }
    
    0 讨论(0)
  • 2021-02-09 22:49

    You can restrict T though using "Substitution Failure Is Not An Error" (SFINAE):

    template <typename T>
    typename std::enable_if<std::is_base_of<bar, T>::value>::type foo()
    {
    
    }
    

    If T is not derived from bar, specialization of the function template will fail and it will not be considered during overload resolution. std::enable_if and std::is_base_of are new components of the C++ Standard Library added in the forthcoming revision, C++0x. If your compiler/Standard Library implementation don't yet support them, you can also find them in C++ TR1 or Boost.TypeTraits.

    0 讨论(0)
提交回复
热议问题