Overloading multiple function objects by reference

前端 未结 2 1053
半阙折子戏
半阙折子戏 2021-01-30 05:19

In C++17, it is trivial to implement an overload(fs...) function that, given any number of arguments fs... satisfying FunctionObject, returns a new

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-30 05:48

    All right, here's the plan: we're going to determine which function object contains the operator() overload that would be chosen if we used a bare-bones overloader based on inheritance and using declarations, as illustrated in the question. We're going to do that (in an unevaluated context) by forcing an ambiguity in the derived-to-base conversion for the implicit object parameter, which happens after overload resolution succeeds. This behaviour is specified in the standard, see N4659 [namespace.udecl]/16 and 18.

    Basically, we're going to add each function object in turn as an additional base class subobject. For a call for which overload resolution succeeds, creating a base ambiguity for any of the function objects that don't contain the winning overload won't change anything (the call will still succeed). However, the call will fail for the case where the duplicated base contains the chosen overload. This gives us a SFINAE context to work with. We then forward the call through the corresponding reference.

    #include 
    #include 
    #include 
    #include 
    
    template 
    struct ref_overloader
    {
       static_assert(sizeof...(Ts) > 1, "what are you overloading?");
    
       ref_overloader(Ts&... ts) : refs{ts...} { }
       std::tuple refs;
    
       template 
       decltype(auto) operator()(Us&&... us)
       {
          constexpr bool checks[] = {over_fails>::value...};
          static_assert(over_succeeds(checks), "overload resolution failure");
          return std::get(refs)(std::forward(us)...);
       }
    
    private:
       template 
       struct pack { };
    
       template 
       struct over_base : U { };
    
       template 
       struct over_base> : Us... 
       { 
           using Us::operator()...; // allow composition
       }; 
    
       template 
       using add_base = over_base<1, 
           ref_overloader<
               over_base<2, U>, 
               over_base<1, Ts>...
           >
       >&; // final & makes declval an lvalue
    
       template 
       struct over_fails : std::true_type { };
    
       template 
       struct over_fails,
          std::void_t>()(std::declval()...)
          )>> : std::false_type 
       { 
       };
    
       // For a call for which overload resolution would normally succeed, 
       // only one check must indicate failure.
       static constexpr bool over_succeeds(const bool (& checks)[sizeof...(Ts)]) 
       { 
           return !(checks[0] && checks[1]); 
       }
    
       static constexpr std::size_t choose_obj(const bool (& checks)[sizeof...(Ts)])
       {
          for(std::size_t i = 0; i < sizeof...(Ts); ++i)
             if(checks[i]) return i;
          throw "something's wrong with overload resolution here";
       }
    };
    
    template auto ref_overload(Ts&... ts)
    {
       return ref_overloader{ts...};
    }
    
    
    // quick test; Barry's example is a very good one
    
    struct A { template  void operator()(T) { std::cout << "A\n"; } };
    struct B { template  void operator()(T*) { std::cout << "B\n"; } };
    
    int main()
    {
       A a;
       B b;
       auto c = [](int*) { std::cout << "C\n"; };
       auto d = [](int*) mutable { std::cout << "D\n"; };
       auto e = [](char*) mutable { std::cout << "E\n"; };
       int* p = nullptr;
       auto ro1 = ref_overload(a, b);
       ro1(p); // B
       ref_overload(a, b, c)(p); // B, because the lambda's operator() is const
       ref_overload(a, b, d)(p); // D
       // composition
       ref_overload(ro1, d)(p); // D
       ref_overload(ro1, e)(p); // B
    }
    

    live example on wandbox


    Caveats:

    • We're assuming that, even though we don't want an overloader based on inheritance, we could inherit from those function objects if we wanted to. No such derived object is created, but the checks done in unevaluated contexts rely on this being possible. I can't think of any other way to bring those overloads into the same scope so that overload resolution can be applied to them.
    • We're assuming that forwarding works correctly for the arguments to the call. Given that we hold references to the target objects, I don't see how this could work without some kind of forwarding, so this seems like a mandatory requirement.
    • This currently works on Clang. For GCC, it looks like the derived-to-base conversion we're relying on is not a SFINAE context, so it triggers a hard error; this is incorrect as far as I can tell. MSVC is super helpful and disambiguates the call for us: it looks like it just chooses the base class subobject that happens to come first; there, it works - what's not to like? (MSVC is less relevant to our problem at the moment, since it doesn't support other C++17 features either).
    • Composition works through some special precautions - when testing the hypothetical inheritance based overloader, a ref_overloader is unwrapped into its constituent function objects, so that their operator()s participate in overload resolution instead of the forwarding operator(). Any other overloader attempting to compose ref_overloaders will obviously fail unless it does something similar.

    Some useful bits:

    • A nice simplified example by Vittorio showing the ambiguous base idea in action.
    • About the implementation of add_base: the partial specialization of over_base for ref_overloader does the "unwrapping" mentioned above to enable ref_overloaders containing other ref_overloaders. With that in place, I just reused it to build add_base, which is a bit of a hack, I'll admit. add_base is really meant to be something like inheritance_overloader, over_base<1, Ts>...>, but I didn't want to define another template that would do the same thing.
    • About that strange test in over_succeeds: the logic is that if overload resolution would fail for the normal case (no ambiguous base added), then it would also fail for all the "instrumented" cases, regardless of what base is added, so the checks array would contain only true elements. Conversely, if overload resolution would succeed for the normal case, then it would also succeed for all the other cases except one, so checks would contain one true element with all the others equal to false.

      Given this uniformity in the values in checks, we can look at just the first two elements: if both are true, this indicates overload resolution failure in the normal case; all the other combinations indicate resolution success. This is the lazy solution; in a production implementation, I would probably go for a comprehensive test to verify that checks really contains an expected configuration.


    Bug report for GCC, submitted by Vittorio.

    Bug report for MSVC.

提交回复
热议问题