简体   繁体   English

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

[英]Simulate generic/templated lambdas on C++11

I got a problem on where I have something like this: 我在哪里有这样的问题:

#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;

I need to make a code that would, for example, call a(b(), c()), with their respective types. 我需要编写一个代码,例如,使用它们各自的类型来调用a(b(),c())。

On C++14 I can easely do this: 在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;
};

Achieving the desired result... is there any way to get the same result on C++11? 实现所需的结果...有什么办法可以在C ++ 11上获得相同的结果? :'( :'(

Also, they can call each other recursively, so a simple ordering here wouldn't help either. 而且,他们可以互相递归调用,因此在这里进行简单的排序也无济于事。

Edit 编辑

I will try to explain better my situation. 我将尽力更好地解释我的情况。

I got an input file like this, for example: 我得到了这样的输入文件,例如:

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;
};

And I need to generate a C++ code that can properly call them. 而且我需要生成一个可以正确调用它们的C ++代码。 I'm trying to infer the return types without needing to define them on the input file. 我试图推断返回类型,而无需在输入文件中定义它们。

From that, I can get the *_BODY specifications, the number of parameters, and the order of calls, but I don't know which type the parameters will be. 由此,我可以获得*_BODY规范,参数数量和调用顺序,但是我不知道参数将是哪种类型。 So I'd need an templated lambda, for example, to do lazy evaluation of the function body. 因此,例如,我需要模板化的lambda来对函数体进行惰性评估。

I can do this with C++14 on GCC and CLang, but this is a commercial project and I need to support Visual Studio 2012 as well. 我可以在GCC和CLang上使用C ++ 14做到这一点,但这是一个商业项目,我也需要支持Visual Studio 2012。 I'm trying to find a workaround, if there is any. 我正在尝试找到解决方法(如果有)。 :( :(

Could do it like this: 可以这样做:

#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;
};

Works fine in clang. 在c中工作正常。 On the other hand, gcc (4.8.1) complains that 另一方面,gcc(4.8.1)抱怨说

sorry, unimplemented: string literal in function template signature

for function a , but you don't really need a result for that; 对于功能a ,但是您实际上不需要结果; it could be just void . 它可能只是void

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM