文章目录
- 一、使用std::variant和std::visit
- 二、使用虚函数
- 三、使用工厂模式管理第三方库的Msg
- 四、尾随逗号
- 1.初始化列表
- 2.枚举
- 3.数组
- 4.结构体或类的成员初始化列表
- 参考
需求点:假设一个第三方库有提供了很多Msg类,这些Msg类都提供了固定的一个成员函数,但是却没有虚基函数。如何在自己的项目代码中更好的使用这些Msg类内?
一、使用std::variant和std::visit
#include <iostream>
#include <memory> // for std::unique_ptr and std::make_unique
#include <string>
#include <utility> // for std::move
#include <variant>
#include <vector>// 外部库 Start
struct MoveMsg {int x;int y;void speak() { std::cout << "Move " << x << ", " << y << '\n'; }
};struct JumpMsg {int height;void speak() { std::cout << "Jump " << height << '\n'; }
};struct SleepMsg {int time;void speak() { std::cout << "Sleep " << time << '\n'; }
};struct ExitMsg {void speak() { std::cout << "Exit" << '\n'; }
};
// 外部库 Endint main() {using Msg = std::variant<MoveMsg, JumpMsg, SleepMsg, ExitMsg>;std::vector<Msg> msgs;msgs.push_back(MoveMsg{1, 2});msgs.push_back(JumpMsg{1});for (auto&& msg : msgs) {std::visit([](auto& msg) { msg.speak(); }, msg);}return 0;
}
二、使用虚函数
C++20语法
#include <iostream>
#include <memory> // for std::unique_ptr and std::make_unique
#include <string>
#include <utility> // for std::move
#include <variant>
#include <vector>// 外部库 Start
struct MoveMsg {int x;int y;void speak() { std::cout << "Move " << x << ", " << y << '\n'; }
};struct JumpMsg {int height;void speak() { std::cout << "Jump " << height << '\n'; }void happy() { std::cout << "happy " << height << '\n'; }
};struct SleepMsg {int time;void speak() { std::cout << "Sleep " << time << '\n'; }
};struct ExitMsg {void speak() { std::cout << "Exit" << '\n'; }
};
// 外部库 Endstruct MsgBase {virtual void speak() = 0;virtual void happy() = 0;virtual std::shared_ptr<MsgBase> clone() const = 0;virtual ~MsgBase() = default;
};//内部代码使用MsgBase去包装库的speak()和happy()函数
template <class Msg>
struct MsgImpl : MsgBase {Msg msg;template <class ...Ts>MsgImpl(Ts &&...ts) : msg{std::forward<Ts>(ts)...} {}void speak() override {msg.speak();}void happy() override {if constexpr (requires {msg.happy();} ){msg.happy();}else{std::cout<< "no happy\n";}}std::shared_ptr<MsgBase> clone() const override {return std::make_shared<MsgImpl<Msg>>(msg);}
};template <class Msg, class ...Ts>
std::shared_ptr<MsgBase> makeMsg(Ts &&...ts) {return std::make_shared<MsgImpl<Msg>>(std::forward<Ts>(ts)...);
}int main() {std::vector<std::shared_ptr<MsgBase>> msgs;msgs.push_back(makeMsg<MoveMsg>(1, 2));msgs.push_back(makeMsg<JumpMsg>(1));for (auto&& msg : msgs) {msg->speak(); msg->happy(); }return 0;
}
C++14写法1
#include <iostream>
#include <memory> // for std::unique_ptr and std::make_unique
#include <string>
#include <utility> // for std::move
#include <variant>
#include <vector>// 外部库 Start
struct MoveMsg {int x;int y;void speak() { std::cout << "Move " << x << ", " << y << '\n'; }
};struct JumpMsg {int height;void speak() { std::cout << "Jump " << height << '\n'; }void happy() { std::cout << "happy " << height << '\n'; }
};struct SleepMsg {int time;void speak() { std::cout << "Sleep " << time << '\n'; }
};struct ExitMsg {void speak() { std::cout << "Exit" << '\n'; }
};
// 外部库 Endstruct MsgBase {virtual void speak() = 0;virtual void happy() = 0;virtual std::shared_ptr<MsgBase> clone() const = 0;virtual ~MsgBase() = default;
};// 特质,用于检测 happy 方法是否存在
template<typename T>
struct has_happy {
private:typedef char YesType[1];typedef char NoType[2];template <typename C> static YesType& test(decltype(&C::happy));template <typename C> static NoType& test(...);public:enum { value = sizeof(test<T>(0)) == sizeof(YesType) };
};// 函数重载用于调用 happy 或者输出 "no happy"
template <typename T>
typename std::enable_if<has_happy<T>::value>::type call_happy(T& t) {t.happy();
}template <typename T>
typename std::enable_if<!has_happy<T>::value>::type call_happy(T&) {std::cout << "no happy\n";
}// MsgImpl 用于包装库的消息类型
template <class Msg>
struct MsgImpl : MsgBase {Msg msg;template <class ...Ts>MsgImpl(Ts &&...ts) : msg{std::forward<Ts>(ts)...} {}void speak() override {msg.speak();}void happy() override {call_happy(msg);}std::shared_ptr<MsgBase> clone() const override {return std::make_shared<MsgImpl<Msg>>(msg);}
};template <class Msg, class ...Ts>
std::shared_ptr<MsgBase> makeMsg(Ts &&...ts) {return std::make_shared<MsgImpl<Msg>>(std::forward<Ts>(ts)...);
}int main() {std::vector<std::shared_ptr<MsgBase>> msgs;msgs.push_back(makeMsg<MoveMsg>(1, 2));msgs.push_back(makeMsg<JumpMsg>(1));for (auto&& msg : msgs) {msg->speak(); msg->happy(); }return 0;
}
has_happy 模板:
- has_happy 模板用于检测 Msg 类中是否有 happy 方法。
- SFINAE 技术用于检查特定方法是否存在。
- test 函数用于确定 happy 方法的存在性,如果存在,返回 sizeof(char),否则返回 sizeof(int)。
call_happy 函数:
- 根据 std::integral_constant 的值,选择调用 happy 方法或输出 “no happy”。
- std::true_type 和 std::false_type 是 std::integral_constant 的特例化,分别表示 true 和 false。
C++14写法2:
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include <type_traits>// 外部库 Start
struct MoveMsg {int x;int y;void speak() { std::cout << "Move " << x << ", " << y << '\n'; }
};struct JumpMsg {int height;void speak() { std::cout << "Jump " << height << '\n'; }void happy() { std::cout << "happy " << height << '\n'; }
};struct SleepMsg {int time;void speak() { std::cout << "Sleep " << time << '\n'; }
};struct ExitMsg {void speak() { std::cout << "Exit" << '\n'; }
};
// 外部库 Endstruct MsgBase {virtual void speak() = 0;virtual void happy() = 0;virtual std::shared_ptr<MsgBase> clone() const = 0;virtual ~MsgBase() = default;
};// 检测 happy 方法存在性的模板
template<typename T>
struct has_happy {// 利用 SFINAE 技术检测 happy 方法template<typename U>static auto test(int) -> decltype(std::declval<U>().happy(), std::true_type{});template<typename>static std::false_type test(...);static constexpr bool value = decltype(test<T>(0))::value;
};// MsgImpl 包装库的消息类型
template <class Msg>
struct MsgImpl : MsgBase {Msg msg;template <class ...Ts>MsgImpl(Ts&&... ts) : msg{std::forward<Ts>(ts)...} {}void speak() override {msg.speak();}void happy() override {call_happy(msg, std::integral_constant<bool, has_happy<Msg>::value>{});}std::shared_ptr<MsgBase> clone() const override {return std::make_shared<MsgImpl<Msg>>(msg);}private:// 当 Msg 有 happy 方法时调用template<typename T>void call_happy(T& t, std::true_type) {t.happy();}// 当 Msg 没有 happy 方法时调用template<typename T>void call_happy(T&, std::false_type) {std::cout << "no happy\n";}
};template <class Msg, class ...Ts>
std::shared_ptr<MsgBase> makeMsg(Ts&&... ts) {return std::make_shared<MsgImpl<Msg>>(std::forward<Ts>(ts)...);
}int main() {std::vector<std::shared_ptr<MsgBase>> msgs;msgs.push_back(makeMsg<MoveMsg>(1, 2));msgs.push_back(makeMsg<JumpMsg>(1));for (auto&& msg : msgs) {msg->speak(); msg->happy(); }return 0;
}
使用特质 has_happy 来检测 happy 方法是否存在。
使用 enable_if 和函数重载来根据特质的值调用不同的实现。
三、使用工厂模式管理第三方库的Msg
需求:假设需要通过不同的输入给这些第三方库的不同Msg构造函数输入值,该怎么办?无法为 Msg 们增加成员函数,只能以重载的形式,外挂追加
#include <iostream>
#include <memory> // for std::unique_ptr and std::make_unique
#include <string>
#include <utility> // for std::move
#include <variant>
#include <vector>
#include <map>// 外部库 Start
struct MoveMsg {int x;int y;void speak() { std::cout << "Move " << x << ", " << y << '\n'; }
};struct JumpMsg {int height;void speak() { std::cout << "Jump " << height << '\n'; }void happy() { std::cout << "happy " << height << '\n'; }
};struct SleepMsg {int time;void speak() { std::cout << "Sleep " << time << '\n'; }
};struct ExitMsg {void speak() { std::cout << "Exit" << '\n'; }
};
// 外部库 Endstruct MsgBase {virtual void speak() = 0;virtual void load() = 0;virtual ~MsgBase() = default;using Ptr = std::shared_ptr<MsgBase>;
};// 无法为 Msg们增加成员函数,只能以重载的形式,外挂追加
namespace msg_extra_funcs { void load(MoveMsg &msg) { std::cin >> msg.x >> msg.y; }void load(JumpMsg &msg) { std::cin >> msg.height; }void load(SleepMsg &msg) { std::cin >> msg.time; }void load(ExitMsg &) {}
} // namespace msg_extra_funcstemplate <class Msg>
struct MsgImpl : MsgBase {Msg msg;void speak() override { msg.speak(); }void load() override { msg_extra_funcs::load(msg); }
};struct MsgFactoryBase {virtual MsgBase::Ptr create() = 0;virtual ~MsgFactoryBase() = default;using Ptr = std::shared_ptr<MsgFactoryBase>;
};template <class Msg>
struct MsgFactoryImpl : MsgFactoryBase {MsgBase::Ptr create() override { return std::make_shared<MsgImpl<Msg>>(); }
};template <class Msg>
MsgFactoryBase::Ptr makeFactory() {return std::make_shared<MsgFactoryImpl<Msg>>();
}struct RobotClass {inline static const std::map<std::string, MsgFactoryBase::Ptr> factories = {{"Move", makeFactory<MoveMsg>()},{"Jump", makeFactory<JumpMsg>()},{"Sleep", makeFactory<SleepMsg>()},{"Exit", makeFactory<ExitMsg>()},};void recv_data() {std::string type;std::cin >> type;try {//建议使用at,而不是[],是因为后者的key如果不存在,则创建一个value=nullptr的itemmsg = factories.at(type)->create();} catch (std::out_of_range &) {std::cout << "no such msg type!\n";return;}msg->load();}void update() {if (msg) msg->speak();}MsgBase::Ptr msg;
};int main() {RobotClass robot;robot.recv_data();robot.update();return 0;
}
工厂常见使用宏
#include <iostream>
#include <memory> // for std::unique_ptr and std::make_unique
#include <string>
#include <utility> // for std::move
#include <variant>
#include <vector>
#include <map>// 外部库 Start
struct MoveMsg {int x;int y;void speak() { std::cout << "Move " << x << ", " << y << '\n'; }
};struct JumpMsg {int height;void speak() { std::cout << "Jump " << height << '\n'; }void happy() { std::cout << "happy " << height << '\n'; }
};struct SleepMsg {int time;void speak() { std::cout << "Sleep " << time << '\n'; }
};struct ExitMsg {void speak() { std::cout << "Exit" << '\n'; }
};
// 外部库 Endstruct MsgBase {virtual void speak() = 0;virtual void load() = 0;virtual ~MsgBase() = default;using Ptr = std::shared_ptr<MsgBase>;
};// 无法为 Msg们增加成员函数,只能以重载的形式,外挂追加
namespace msg_extra_funcs { void load(MoveMsg &msg) { std::cin >> msg.x >> msg.y; }void load(JumpMsg &msg) { std::cin >> msg.height; }void load(SleepMsg &msg) { std::cin >> msg.time; }void load(ExitMsg &) {}
} // namespace msg_extra_funcstemplate <class Msg>
struct MsgImpl : MsgBase {Msg msg;void speak() override { msg.speak(); }void load() override { msg_extra_funcs::load(msg); }
};struct MsgFactoryBase {virtual MsgBase::Ptr create() = 0;virtual ~MsgFactoryBase() = default;using Ptr = std::shared_ptr<MsgFactoryBase>;
};template <class Msg>
struct MsgFactoryImpl : MsgFactoryBase {MsgBase::Ptr create() override { return std::make_shared<MsgImpl<Msg>>(); }
};template <class Msg>
MsgFactoryBase::Ptr makeFactory() {return std::make_shared<MsgFactoryImpl<Msg>>();
}struct RobotClass {inline static const std::map<std::string, MsgFactoryBase::Ptr> factories = {//define这里的宏以后,用完就undef掉,否则会如果其他人引入了该头文件,会影响别人的宏
#define PRE_MSG(Type) {#Type, makeFactory<Type##Msg>()},PRE_MSG(Move)PRE_MSG(Move)PRE_MSG(Jump)PRE_MSG(Sleep)PRE_MSG(Exit)
#undef PRE_MSG// {"Move", makeFactory<MoveMsg>()},// {"Jump", makeFactory<JumpMsg>()},// {"Sleep", makeFactory<SleepMsg>()},// {"Exit", makeFactory<ExitMsg>()},};void recv_data() {std::string type;std::cin >> type;try {msg = factories.at(type)->create();} catch (std::out_of_range &) {std::cout << "no such msg type!\n";return;}msg->load();}void update() {if (msg) msg->speak();}MsgBase::Ptr msg;
};int main() {RobotClass robot;robot.recv_data();robot.update();return 0;
}
四、尾随逗号
在C++中,初始化列表中的最后一个元素后面可以有一个逗号,这被称为“尾随逗号”(trailing comma)。这种语法在初始化列表、枚举、和数组中都是允许的。使用尾随逗号有几个好处:
- 方便添加新元素:当你需要在列表末尾添加新的元素时,不需要修改前一行的逗号。这减少了编辑错误的可能性。
- 更清晰的版本控制:在使用版本控制系统(如Git)时,如果每一行元素后都有逗号,添加新元素时只会新增一行变更,而不是修改和新增两行。
- 一致性和可读性:在某些情况下,尾随逗号可以使代码更加一致和易读,尤其是在长列表中。
1.初始化列表
在初始化列表中,你可以在最后一个元素后添加一个逗号。
#include <iostream>
#include <map>
#include <string>int main() {// 使用{}初始化mapstd::map<std::string, int> myMap = {{"apple", 1},{"banana", 2},{"orange", 3}, // 尾随逗号};// 访问map中的元素std::cout << "apple: " << myMap["apple"] << std::endl;std::cout << "banana: " << myMap["banana"] << std::endl;std::cout << "orange: " << myMap["orange"] << std::endl;return 0;
}
2.枚举
在定义枚举类型时,也可以在最后一个枚举成员后加上逗号。
#include <iostream>enum Fruit {Apple,Banana,Orange, // 尾随逗号
};int main() {Fruit myFruit = Apple;std::cout << "Fruit value: " << myFruit << std::endl;return 0;
}
3.数组
在初始化数组时,可以在最后一个元素后添加一个逗号。
#include <iostream>int main() {int myArray[] = {1, 2, 3, 4, 5,}; // 尾随逗号// 访问数组中的元素for (int i = 0; i < 5; ++i) {std::cout << "myArray[" << i << "]: " << myArray[i] << std::endl;}return 0;
}
4.结构体或类的成员初始化列表
在初始化结构体或类的成员时,也可以使用尾随逗号。
#include <iostream>struct Point {int x, y;
};int main() {Point p = {1, 2,}; // 尾随逗号std::cout << "Point: (" << p.x << ", " << p.y << ")" << std::endl;return 0;
}
参考
- 【C++】类型擦除 + 工厂模式,告别 if-else
- 代码