gpt4 book ai didi

C++-17 可变参数模板 : capture both return type and argument types for a callback argument

转载 作者:行者123 更新时间:2023-11-27 22:50:43 26 4
gpt4 key购买 nike

我在这个谜题上花了好几个星期,我想我可以把它作为对这里的 C++ 可变参数模板人群的挑战。如果可以,我敢打赌您会在大约 10 秒内告诉我怎么做。

假设我有一组 C++ 17 函数,每个函数都有自己的返回类型(或 void),每个都有自己的参数类型。为简单起见,POD 参数和指向类的指针、可变数量的 args 等的混合。所以两个例子:

int somefunc(int x, double d) { return x + (int)d; }
void otherfunc(Foo *a, Bar *b, int x) { ... }

我的目标是通过构建一个捕获完整类型集的可变参数函数,在没有注释的情况下进行静态编译时反射。因此为了讨论,我们可以说我们的函数是 RT f(T1 a, T2 b, ...) 类型。我的上下文是我正在为 RPC 和多播系统构建一个新的(并且更好的)数据编码层,这些回调实际上将在收到字节数组时完成,我需要将其解编码并转换为正确的类型:从我的字节数组的第一个字节中提取的 int,或者一个新的 Foo(char*),其中 Foo 本身有一个工厂方法来执行提升等。

静态反射是什么意思?我想要一个 const std::list,我可以在其中将 typeid(RT).hash_code() 之类的东西放入我的 Info 类中,或者可能是指向我的每个参数类别的构造函数的指针(POD 构造函数基本上将传入字节序列为 int*,然后返回 int;类构造函数将调用工厂方法)。

好的,长序言,现在是失败的尝试:这是我的尝试。 C++17 根本不喜欢它(似乎可以正确绑定(bind) RT 但无法绑定(bind) Rest,可能是因为 Rest 实际上是 RT 捕获的整体函数类型中的参数类型列表)。有什么想法吗?

class Info
{
int rt, at; Info *next;
Info(int r, int a, Info* nxt) { rt = r; at = a; next = nxt; }
};

template<typename RT>
Info *Scan(RT cb())
{
return nullptr;
}

template<typename RT, typename T, typename Rest...> Info* Scan(RT cb(T x, Rest... args))
{
return new Info(typeid(RT).hash_code(), typeid(T).hash_code(), Scan<RT, Rest...>(cb(args...));
};

int TestMethod(int x, int y)
{
return 0;
}

int main()
{
Scan(TestMethod);
return 0;
}

最佳答案

你不需要一个单独的类或递归,你可以只返回一个 std::array通过在 hash_code 上扩展参数参数包来获取哈希码调用:

template <typename RT, typename... Args> 
std::array<size_t, (sizeof...(Args) + 1)>
Scan (RT (*) (Args...))
{
return { typeid(RT).hash_code(), typeid(Args).hash_code()... };
}

关于C++-17 可变参数模板 : capture both return type and argument types for a callback argument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37439985/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com