簡體   English   中英

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

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

我在哪里有這樣的問題:

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

在c中工作正常。 另一方面,gcc(4.8.1)抱怨說

sorry, unimplemented: string literal in function template signature

對於功能a ,但是您實際上不需要結果; 它可能只是void

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM