1 // Copyright 2016 The SwiftShader Authors. All Rights Reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 #ifndef rr_Routine_hpp 16 #define rr_Routine_hpp 17 18 #include <memory> 19 20 namespace rr { 21 22 class Routine 23 { 24 public: 25 Routine() = default; 26 virtual ~Routine() = default; 27 28 virtual const void *getEntry(int index = 0) const = 0; 29 }; 30 31 // RoutineT is a type-safe wrapper around a Routine and its callable entry, returned by FunctionT 32 template<typename FunctionType> 33 class RoutineT; 34 35 template<typename Return, typename... Arguments> 36 class RoutineT<Return(Arguments...)> 37 { 38 public: 39 RoutineT() = default; 40 RoutineT(const std::shared_ptr<Routine> & routine)41 explicit RoutineT(const std::shared_ptr<Routine> &routine) 42 : routine(routine) 43 { 44 if(routine) 45 { 46 callable = reinterpret_cast<CallableType>(const_cast<void *>(routine->getEntry(0))); 47 } 48 } 49 operator bool() const50 operator bool() const 51 { 52 return callable != nullptr; 53 } 54 55 template<typename... Args> operator ()(Args &&...args) const56 Return operator()(Args &&... args) const 57 { 58 return callable(std::forward<Args>(args)...); 59 } 60 getEntry() const61 const void *getEntry() const 62 { 63 return reinterpret_cast<void *>(callable); 64 } 65 66 private: 67 std::shared_ptr<Routine> routine; 68 using CallableType = Return (*)(Arguments...); 69 CallableType callable = nullptr; 70 }; 71 72 } // namespace rr 73 74 #endif // rr_Routine_hpp 75