template class restriction

前端 未结 2 1103
滥情空心
滥情空心 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:49

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

    template 
    typename std::enable_if::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.

提交回复
热议问题