折叠常数的C++程序
我正在用C++11编写一个函数,它采用constant1+constant2形式的表达式并折叠它们。constant1和constant2存储在std::string中,它们的类型存储在enum TypeEnum中 我的尝试如下:折叠常数的C++程序,c++,C++,我正在用C++11编写一个函数,它采用constant1+constant2形式的表达式并折叠它们。constant1和constant2存储在std::string中,它们的类型存储在enum TypeEnum中 我的尝试如下: #include <iostream> short int fold(short int a, short int b){return a+b;} int fold(int a, int b){return a+b;} int main(int a
#include <iostream>
short int fold(short int a, short int b){return a+b;}
int fold(int a, int b){return a+b;}
int main(int argc, char **argv){
std::cout<<fold((short)32767,(short)1)<<std::endl;
std::cout<<fold(32767,(short)1)<<std::endl; return 0;
}
节目:
输出:
9223372036854775807
-2147483648
如您所见,功能折叠变得非常混乱和漫长。我想知道是否有更好的方法可以做到这一点。我更愿意改变和简化问题,并编写如下代码:
#include <iostream>
short int fold(short int a, short int b){return a+b;}
int fold(int a, int b){return a+b;}
int main(int argc, char **argv){
std::cout<<fold((short)32767,(short)1)<<std::endl;
std::cout<<fold(32767,(short)1)<<std::endl; return 0;
}
但是,如果您注意到如果将C++更改为“int”和“int”,则由于C++的升级规则缺乏连续性,代码将不再工作。
< P>使用开关{}结构:switch(typeConst1){
case INT:
switch(typeConst2){
case INT:
return stoi(constant1) + stoi(constant2);
case LONG_INT:
return stoi(constant1) + stol(constant2);
case LONG_LONG_INT:
return stoi(constant1) + stoll(constant2);
case UNSIGNED_INT:
return stoi(constant1) + stol(constant2);
case UNSIGNED_LONG_INT:
return stoi(constant1) + stoul(constant2);
case UNSIGNED_LONG_LONG_INT:
return stoi(constant1) + stoull(constant2);
case LONG_INT:
//...
根据我的要求,传递给fold的constant1和constant2的类型必须是字符串。这个函数实际上是我正在进行的一个更大项目的一部分。这个问题与不断折叠无关,事实上,与折叠几乎没有关系。你所要求的是动态的types@PasserBy-你说得对。修复了标记。您可以将这两个参数转换为long-long-int,而不是拼写36个无意义的大小写,因为这就是您的返回类型,并且完全忽略了类型常量。顺便说一句,您没有写一个函数来折叠常数或类似的东西,您写的是一个函数来添加两个数字。@n.m.-将两个参数转换为long long int是不正确的,因为对于任意两个int a和b,long longa+long long b==long longa+b是没有定义的行为,只有无符号算术才允许换行。谢谢你的建议。有了switch,代码看起来当然更好了,但行数还是一样的。我希望能找到一个能减少折叠尺寸的解决方案。