How to call a templated function if it exists, and something else otherwise?

后端 未结 7 493
忘掉有多难
忘掉有多难 2021-01-30 10:58

I want to do something like

template 
void foo(const T& t) {
   IF bar(t) would compile
      bar(t);
   ELSE
      baz(t);
}
7条回答
  •  感情败类
    2021-01-30 11:36

    litb has given you a very good answer. However, I wonder whether, given more context, we couldn't come up with something that's less generic, but also less, um, elaborate?

    For example, what types can be T? Anything? A few types? A very restricted set which you have control over? Some classes you design in conjunction with the function foo? Given the latter, you could simple put something like

    typedef boolean has_bar_func;
    

    into the types and then switch to different foo overloads based on that:

    template 
    void foo_impl(const T& t, boolean /*has_bar_func*/);
    template 
    void foo_impl(const T& t, boolean /*has_bar_func*/);
    
    template 
    void foo(const T& t) {
      foo_impl( t, typename T::has_bar_func() );
    }
    

    Also, can the bar/baz function have just about any signature, is there a somewhat restricted set, or is there just one valid signature? If the latter, litb's (excellent) fallback idea, in conjunction with a meta-function employing sizeof might be a bit simpler. But this I haven't explored, so it's just a thought.

提交回复
热议问题