c++ - 接受 cpp 中的任何类型的参数

标签 c++

我想要一个可以接受任何类型参数的函数,然后在实现中可以检查类型是否为整数,然后可以抛出消息。例如,可以像下面这样调用该函数,

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::anystd::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();
}

Demo


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();
}

Demo

关于c++ - 接受 cpp 中的任何类型的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75494903/

相关文章:

c++ - 对内存分配和构造函数的调用是否可以与执行 "new"表达式所需的其他操作交错?

c++ - 从“const char [2]”到非标量类型“Persona”的转换请求

c++ - 如何在一段时间内更新 QLabel?

c++ - 使用可替换阶段在 C++ 中建模管道

C++:在删除时检查 NULL

c++ - 二进制表达式的无效操作数

c++ - CMake 添加带有子目录的库

c++ - 强制 recv (Windows C++) 函数阻塞,直到读取 N 个字节

c++ - cocos2d-x EventDispatcher 不再是单例了吗?

c++ - 滚动后 MFC 控件消失