Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstdint>
- #include <type_traits>
- #include <cstdio>
- namespace detail {
- template<typename, typename T>
- struct has_serialise {
- static_assert(std::integral_constant<T, false>::value, "Second template parameter needs to be function type");
- };
- template<typename C, typename Ret, typename... Args>
- struct has_serialise<C, Ret(Args...)> {
- private:
- template<typename T>
- static constexpr auto check(T*)
- ->typename
- std::is_same<
- decltype( std::declval<T>().serialise(std::declval<Args>()...) ),
- Ret
- >::type;
- template<typename>
- static constexpr std::false_type check(...);
- typedef decltype(check<C>(0)) type;
- public:
- static constexpr bool value = type::value;
- };
- }
- template<typename Serializable, std::enable_if_t<detail::has_serialise<Serializable, uint32_t(uint8_t**)>::value == true, int> = 0>
- uint32_t serialize(Serializable& object, uint8_t** buffer) {
- return object.serialise(buffer);
- }
- template<typename Serializable, std::enable_if_t<!detail::has_serialise<Serializable, uint32_t(uint8_t**)>::value == true, int> = 0>
- uint32_t serialize(Serializable& object, uint8_t** buffer) {
- static_assert(sizeof(Serializable) == 0, "Serialise method does not exist");
- return 0;
- }
- class MyClass{
- public:
- uint32_t serialise(uint8_t** buffer){
- (*buffer)[0] = 1;
- return 25;
- }
- };
- class NonStandartClass{
- }
- int main(){
- MyClass object;
- NonStandartClass object2;
- uint8_t buf[256];
- uint8_t* buffer = &buf[0];
- //alloc it in real case
- uint32_t sz = serialize(object, &buffer);
- std::printf("Size of serialised object: %d \n", sz);
- //Uncoment to get compile time error
- //sz = serialize(object2, &buffer);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement