1 // Copyright 2021 gRPC authors. 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 GRPC_SRC_CORE_LIB_GPRPP_CPP_IMPL_OF_H 16 #define GRPC_SRC_CORE_LIB_GPRPP_CPP_IMPL_OF_H 17 18 namespace grpc_core { 19 20 // Declares CppType to be the backing implementation of CType. 21 // Use via the curiously recursive template: 22 // class Foo : public CppImplOf<Foo, grpc_foo> {}; 23 // Provides casting methods each way. 24 // grpc_foo should be `typedef struct grpc_foo grpc_foo` and otherwise 25 // not defined. 26 template <typename CppType, typename CType> 27 class CppImplOf { 28 public: 29 // Convert the C struct to C++ FromC(CType * c_type)30 static CppType* FromC(CType* c_type) { 31 return reinterpret_cast<CppType*>(c_type); 32 } 33 FromC(const CType * c_type)34 static const CppType* FromC(const CType* c_type) { 35 return reinterpret_cast<const CppType*>(c_type); 36 } 37 38 // Retrieve a c pointer (of the same ownership as this) c_ptr()39 CType* c_ptr() { 40 return reinterpret_cast<CType*>(static_cast<CppType*>(this)); 41 } 42 43 protected: 44 ~CppImplOf() = default; 45 }; 46 47 } // namespace grpc_core 48 49 #endif // GRPC_SRC_CORE_LIB_GPRPP_CPP_IMPL_OF_H 50