我遇到了类似这样的问题:
#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;
我需要制作一个代码,例如,用它们各自的类型调用(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。我试图找到一个解决方法,如果有的话。 :(
答案 0 :(得分:1)
可以这样做:
#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
for function a
,但你真的不需要结果;它可能只是void
。