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

后端 未结 7 490
忘掉有多难
忘掉有多难 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:38

    I think litb's solution works, but is overly complex. The reason is that he's introducing a function fallback::bar(...) which acts as a "function of last resort", and then goes to great lengths NOT to call it. Why? It seems we have a perfect behavior for it:

    namespace fallback {
        template
        inline void bar(T const& t, ...)
        {
            baz(t);
        }
    }
    template
    void foo(T const& t)
    {
        using namespace fallback;
        bar(t);
    }
    

    But as I indicated in a comment to litb's original post, there are many reasons why bar(t) could fail to compile, and I'm not certain this solution handles the same cases. It certainly will fail on a private bar::bar(T t)

提交回复
热议问题