我想要一个可以接受任何类型参数的函数,然后在实现中可以检查类型是否为整数,然后可以抛出消息。例如,可以像下面这样调用该函数,
add(10, 12);
Output : "correct input. addition is 22"
add(10, "hello")
Output : "wrong input"
add(10)
Output : "wrong input! missing arguments"
是否可以用 C++ 实现这一点?
使用重载,我将不得不创建所有可能组合的函数,例如 (int, double)、(double, int)、(int, string)、(string, int) 等,那么还有其他方法吗?
最佳答案
自 C++17 起,您可以使用 std::any
和 std::any_cast
:
#include <any>
#include <iostream>
void add(const std::any& a = "", const std::any& b = "")
{
try {
const int ia = std::any_cast<int>(a);
const int ib = std::any_cast<int>(b);
std::cout << "correct input. addition is " << ia + ib << std::endl;
}
catch (...) {
std::cout << "wrong input" << std::endl;
}
}
int main()
{
add(10, "hello");
add(10, 12);
add(10);
add();
}
C++17 之前的解决方案:
#include <iostream>
void add(int a, int b)
{
std::cout << "correct input. addition is " << a + b << std::endl;
}
template<typename... Ts>
void add(Ts...)
{
std::cout << "wrong input" << std::endl;
}
int main()
{
add(10, "hello");
add(10, 12);
add(10);
add();
}
关于c++ - 接受 cpp 中的任何类型的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75494903/