SFINAE: checking the existence of a function breaks when the overload is moved to other namespaces

前端 未结 2 786
予麋鹿
予麋鹿 2020-12-19 17:53

I want to check for the existence of a function in a specific namespace using SFINAE. I have found SFINAE to test a free function from another namespace which does the job,

2条回答
  •  心在旅途
    2020-12-19 18:19

    In addition to DyP's answer and following his comment:

    If your function bar took any arguments, you could make use of dependent name lookup to make it work (w/o a second overload of bar).

    Indeed in my real code bar() does take arguments.

    As a side question, is there any way to achieve correct SFINAE detection without polluting the global namespace...

    So yes, dependent name lookup works like a charm. For the sake of completeness, and in case it can help others in the future, here's my now perfectly working code:

    #define ENABLE_FOO_BAR 1
    
    namespace foo {
      #if ENABLE_FOO_BAR
        int bar(int);
      #endif
    }
    
    namespace feature_test {
      namespace detail {
        using namespace foo;
        template decltype(bar(std::declval())) test(int);
        template void test(...);
      }
      static constexpr bool has_foo_bar = std::is_same(0)), int>::value;
      static_assert(has_foo_bar == ENABLE_FOO_BAR, "something went wrong");
    }
    

    All credit goes to DyP, I don't believe I'd have thought about this by myself.

提交回复
热议问题