我制作了一个模板和一个自动函数,比较2个值并返回最小值.这是我的代码:
#include <iostream>
using namespace std;
// Template with a value returning function: PrintSmaller
template <typename T, typename U>
auto PrintSmaller(T NumOne, U NumTwo) {
if (NumOne > NumTwo) {
return NumTwo;
}
else {
return NumOne;
}
}
int main() {
int iA = 345;
float fB = 23.4243;
cout << PrintSmaller(iA, fB) << endl;
cout << PrintSmaller(fB, iA) << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但它不会编译,我在VS 2015上得到这个错误: 错误C3487'int':所有返回表达式必须推导为相同的类型:以前它是'浮动'
但是,如果我删除if语句并像这样编写PrintSmaller函数它没有问题:
auto PrintSmaller(T NumOne, U NumTwo) …Run Code Online (Sandbox Code Playgroud) 我有点困惑.在开发基于预定义参数的一个函数期间,根据它们的类型传递给sprintf函数所需的精确参数,我发现了非常奇怪的行为(类似于"这是%f%d示例",typeFloat,typeInt).
请查看以下剥离的工作代码:
struct Param {
enum { typeInt, typeFloat } paramType;
union {
float f;
int i;
};
};
int _tmain(int argc, _TCHAR* argv[])
{
Param p;
p.paramType = Param::typeInt;
p.i = -10;
char chOut[256];
printf( "Number is %d\n", p.paramType == Param::typeInt ? p.i : p.f );
printf( "Number is %f\n", p.paramType == Param::typeInt ? p.i : p.f );
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我的预期产量将是 printf( "Number is %d\n", p.paramType == Param::typeInt ? p.i : p.f );
Number is -10
Run Code Online (Sandbox Code Playgroud)
但它确实打印出来了
Number …Run Code Online (Sandbox Code Playgroud) 我想cv::VideoCapture有条件地调用构造函数.如果argc == 2,则用户指定了视频文件,我想加载它.否则使用默认摄像头.
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
int main(int argc, char* argv[])
{
VideoCapture cap(argc == 2 ? argv[1] : 0);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我编译并运行它
$ g++ -g -Wall -o main main.cpp `pkg-config opencv --cflags --libs`
$ ./main
Run Code Online (Sandbox Code Playgroud)
但遗憾的是它似乎没有用,我得到了
OpenCV: Couldn't read movie file ""
Run Code Online (Sandbox Code Playgroud)
三元运算符在一种情况下返回一个字符串,在另一种情况下返回一个整数.我认为这是行不通的,因为我不知道C++构造函数的一些特性.
做我想要的最干净的方法是什么?我可以不使用new这样做,所以我不必在程序结束时自己释放内存吗?
#include <stdio.h>
int main()
{ int x = 1;
short int i = 2;
float f = 3;
if(sizeof((x == 2) ? f : i) == sizeof(float))
printf("float\n");
else if (sizeof((x == 2) ? f : i) == sizeof(short int))
printf("short int\n");
}
Run Code Online (Sandbox Code Playgroud)
这里的表达式((x == 2) ? f : i)计算i类型为short int的类型.. short int = 2的大小,而sizeof float是4 byts.output应该是"short int"但是我得到输出"float"