mirror of
https://github.com/Light-City/CPlusPlusThings.git
synced 2026-03-20 20:05:07 +08:00
support bazel complie this project and format code.
This commit is contained in:
35
learn_class/modern_cpp_30/SFINAE/sfinae paper/serialize.cpp
Normal file
35
learn_class/modern_cpp_30/SFINAE/sfinae paper/serialize.cpp
Normal file
@@ -0,0 +1,35 @@
|
||||
//
|
||||
// Created by light on 20-1-6.
|
||||
//
|
||||
|
||||
#include <boost/hana.hpp>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include "structData.h"
|
||||
using namespace std;
|
||||
|
||||
namespace hana = boost::hana;
|
||||
// 检查类型是否有一个serialize方法
|
||||
auto hasSerialize = hana::is_valid([](auto &&x) -> decltype(x.serialize()) {});
|
||||
|
||||
// 序列化任意对象
|
||||
template<typename T>
|
||||
std::string serialize(T const &obj) {
|
||||
return hana::if_(hasSerialize(obj),
|
||||
[](auto &x) { return x.serialize(); },
|
||||
[](auto &x) { return to_string(x); }
|
||||
)(obj);
|
||||
}
|
||||
|
||||
|
||||
|
||||
int main() {
|
||||
A a;
|
||||
B b;
|
||||
C c;
|
||||
std::cout << serialize(a) << std::endl;
|
||||
std::cout << serialize(b) << std::endl;
|
||||
std::cout << serialize(c) << std::endl;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user