1 // Copyright 2022 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef BASE_FUNCTIONAL_OVERLOADED_H_ 6 #define BASE_FUNCTIONAL_OVERLOADED_H_ 7 8 namespace base { 9 10 // absl::visit() needs to be called with a functor object, such as 11 // 12 // struct Visitor { 13 // std::string operator()(const PackageA& source) { 14 // return "PackageA"; 15 // } 16 // 17 // std::string operator()(const PackageB& source) { 18 // return "PackageB"; 19 // } 20 // }; 21 // 22 // absl::variant<PackageA, PackageB> var = PackageA(); 23 // return absl::visit(Visitor(), var); 24 // 25 // `Overloaded` enables the above code to be written as: 26 // 27 // absl::visit( 28 // Overloaded{ 29 // [](const PackageA& pack) { return "PackageA"; }, 30 // [](const PackageB& pack) { return "PackageB"; }, 31 // }, var); 32 // 33 // Note: Overloads must be implemented for all the variant options. Otherwise, 34 // there will be a compilation error. 35 // 36 // This struct inherits operator() method from all its base classes. 37 // Introduces operator() method from all its base classes into its definition. 38 template <typename... Callables> 39 struct Overloaded : Callables... { 40 using Callables::operator()...; 41 }; 42 43 // Uses template argument deduction so that the `Overloaded` struct can be used 44 // without specifying its template argument. This allows anonymous lambdas 45 // passed into the `Overloaded` constructor. 46 template <typename... Callables> 47 Overloaded(Callables...) -> Overloaded<Callables...>; 48 49 } // namespace base 50 51 #endif // BASE_FUNCTIONAL_OVERLOADED_H_ 52