【发布时间】:2021-04-13 15:05:28
【问题描述】:
我有一个基于事件的应用程序。 问题是我有很多不同类型的事件,有些课程听了很多。
目前,当我想接收事件时,我创建了一个以消息类型为参数的函数并订阅它。 我想要一个函数来接收所有事件,然后调用函数来处理事件。 这主要是为了更清楚地了解我的课程。 当然,我希望成本尽可能低,如果不是没有的话。
我已经找到了一种方法来做到这一点,我认为它不需要额外的成本,因为它应该在编译时处理。
我想确认是这种情况 我想知道这是否是一种好的做法或可能会给我带来问题的东西。
#include <iostream>
#include <vector>
#include <functional>
using namespace std;
enum class Type {
Test, Test2
};
struct Test {
vector<int>::iterator b;
vector<int>::iterator e;
};
struct Test2 {
int a = 0;
};
template<Type type>
void test(uintptr_t k) {
if constexpr(type == Type::Test) {
auto p = reinterpret_cast<Test*>(k);
for (auto i = p->b; i != p->e; ++i) cout << *i << ' ';
cout << '\n';
} else if constexpr(type == Type::Test2) {
auto p = reinterpret_cast<Test2*>(k);
cout << p->a << '\n';
}
}
int main() {
Test2 v{10};
auto a = reinterpret_cast<uintptr_t>(&v);
std::function<void(uintptr_t)> f_display = test<Type::Test2>;
f_display(a);
return 0;
}
【问题讨论】:
-
由于您需要显式提供测试类型,因此您不妨拥有一堆
test重载,每个重载都有一个Type::Test类型。 -
v2在哪里声明?还是应该是v? -
std::variant<Test*, Test2*>? -
发布的代码无法编译。没有
v2,v不是指针。我猜你的意思是&v2并且你希望变量被称为v2? -
以这种方式编写代码而不是使用重载函数或模板特化有什么意义?你可以让它
test<Test2>工作,你不需要reinterpret_cast
标签: c++ templates optimization