Advertisement
Guest User

Untitled

a guest
Oct 26th, 2016
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. #include <cstdint>
  2. #include <type_traits>
  3. #include <cstdio>
  4. namespace detail {
  5. template<typename, typename T>
  6. struct has_serialise {
  7. static_assert(std::integral_constant<T, false>::value, "Second template parameter needs to be function type");
  8. };
  9. template<typename C, typename Ret, typename... Args>
  10. struct has_serialise<C, Ret(Args...)> {
  11. private:
  12. template<typename T>
  13. static constexpr auto check(T*)
  14. ->typename
  15. std::is_same<
  16. decltype( std::declval<T>().serialise(std::declval<Args>()...) ),
  17. Ret
  18. >::type;
  19. template<typename>
  20. static constexpr std::false_type check(...);
  21.  
  22. typedef decltype(check<C>(0)) type;
  23. public:
  24. static constexpr bool value = type::value;
  25.  
  26. };
  27. }
  28. template<typename Serializable, std::enable_if_t<detail::has_serialise<Serializable, uint32_t(uint8_t**)>::value == true, int> = 0>
  29. uint32_t serialize(Serializable& object, uint8_t** buffer) {
  30. return object.serialise(buffer);
  31. }
  32. template<typename Serializable, std::enable_if_t<!detail::has_serialise<Serializable, uint32_t(uint8_t**)>::value == true, int> = 0>
  33. uint32_t serialize(Serializable& object, uint8_t** buffer) {
  34. static_assert(sizeof(Serializable) == 0, "Serialise method does not exist");
  35. return 0;
  36. }
  37.  
  38. class MyClass{
  39. public:
  40. uint32_t serialise(uint8_t** buffer){
  41. (*buffer)[0] = 1;
  42. return 25;
  43. }
  44. };
  45. class NonStandartClass{
  46. }
  47.  
  48. int main(){
  49. MyClass object;
  50. NonStandartClass object2;
  51. uint8_t buf[256];
  52. uint8_t* buffer = &buf[0];
  53. //alloc it in real case
  54. uint32_t sz = serialize(object, &buffer);
  55. std::printf("Size of serialised object: %d \n", sz);
  56. //Uncoment to get compile time error
  57. //sz = serialize(object2, &buffer);
  58. return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement