如果存在一个函数需要处理不同类型的传参,可以考虑用模板
代码举例
/*
* @FilePath: /template.cpp
* @Author: Wilson
* @Descripttion: 模板举例
* @Date: 2020-12-28 11:21:44
* @LastEditors: Wilson
* @LastEditTime: 2020-12-28 11:58:34
*/
#include <iostream>
#include <string>
//定义类型T和U
template <typename T, typename U>
auto say(T name, U word)
{
std::cout << name <<" say: " << word << std::endl;
return true;
}
int main()
{
//传递整型,输出 John say: 1
say("John", 1);
//传递字符串,输出 Keil say: hi
say("Keil", "hi");
//传递浮点型,输出 Mike say: 66.666
say("Mike", 66.666);
return 0;
}
cmake工程文件
cmake_minimum_required(VERSION 2.8)
set(APPNAME demo)
project(${APPNAME})
SET(CMAKE_BUILD_TYPE "Debug")
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++17 -pthread -g -W")
add_executable(${APPNAME}
template.cpp
)