gpt4 book ai didi

c++ - 在 C++11 上模拟通用/模板化 lambda

转载 作者:行者123 更新时间:2023-11-28 07:25:56 24 4
gpt4 key购买 nike

我遇到这样的问题:

#define A_BODY printf("b is %s and c is %d, typeless! :3\n", b, c);
#define B_BODY return "test";
#define C_BODY return 42;

我需要编写一个代码,例如,调用 a(b(), c()),以及它们各自的类型。

在 C++14 上我可以轻松地做到这一点:

template<typename B, typename C> auto a(B &&b, C &&c) {
A_BODY
};
auto b() {
B_BODY
};
auto c() {
C_BODY
};

int main() {
auto _b = b();
auto _c = c();
auto _a = a(_b, _c);

return 0;
};

实现预期的结果...有什么方法可以在 C++11 上获得相同的结果吗? :'(

此外,它们可以递归地相互调用,因此在这里简单的排序也无济于事。

编辑

我会尝试更好地解释我的情况。

我有一个这样的输入文件,例如:

a is b c {
printf("b is %s and c is %d\n", b, c);
if(c > 42)
printf("c is bigger than the truth!\n");
return strlen(b) + c;
};
b is {
return "test";
};
c is {
return 42;
};

而且我需要生成可以正确调用它们的 C++ 代码。我正在尝试推断返回类型,而无需在输入文件中定义它们。

从那里,我可以获得*_BODY 规范、参数数量和调用顺序,但我不知道参数是哪种类型。因此,我需要一个模板化的 lambda,例如,对函数体进行惰性求值。

我可以在 GCC 和 CLang 上使用 C++14 来做到这一点,但这是一个商业项目,我还需要支持 Visual Studio 2012。我正在尝试找到解决方法(如果有的话)。 :(

最佳答案

可以这样做:

#define A_EXPR printf("b is %s and c is %d, typeless! :3\n", b, c)
#define B_EXPR "test"
#define C_EXPR 42

template<typename B, typename C> auto a(B &&b, C &&c)
-> decltype(A_EXPR) { return A_EXPR; }
auto b() -> decltype(B_EXPR) { return B_EXPR; }
auto c() -> decltype(C_EXPR) { return C_EXPR; }

int main() {
auto _b = b();
auto _c = c();
auto _a = a(_b, _c);
return 0;
};

在 clang 中工作正常。另一方面,gcc (4.8.1) 提示

sorry, unimplemented: string literal in function template signature

对于函数a,但你并不真的需要它的结果;它可能只是 void

关于c++ - 在 C++11 上模拟通用/模板化 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18750965/

24 4 0
文章推荐: C++动态数据结构
文章推荐: c++ - QScrollArea 中没有显示任何内容
文章推荐: html -
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com