简体   繁体   English

C ++函数对象参数

[英]C++ Functions object arguments

How do I have a function that takes in any number of arguments then check its data type accordingly? 我如何有一个函数,该函数接受任意数量的参数,然后相应地检查其数据类型? I understand that in java its Objects..arguments then doing instanceof to check the data type, but in C++? 我知道在Java中它的Objects..arguments然后执行instanceof检查数据类型,但是在C ++中呢?

basically something like converting this into C++ 基本上就像将其转换为C ++

public int Testing(String sql, Object...arguments) throws SQLException{

    PreparedStatement ps = con.prepareStatement(sql);
    for(int i=0; i< arguments.length; i++){
        if (arguments[i] instanceof String)
            ps.setString(i+1, arguments[i].toString());
        else if (arguments[i] instanceof Integer)
            ps.setInt(i+1, Integer.parseInt(arguments[i].toString()));
    }
    return ps.executeUpdate();
}

While you could use variadic templates or something similar, I'd suggest just using a variant library such as boost::variant , keeping it simple: 虽然您可以使用可变参数模板或类似的模板,但我建议您仅使用诸如boost::variant类的变体库,保持简单:

#include <boost/any.hpp>
#include <iostream>
#include <string>

int Testing(std::initializer_list<boost::any> args) {
        for(const auto &arg : args) {
                std::cout << "Arg type: " << arg.type().name();
                if(arg.type() == typeid(int)) { // Check for int
                        int value = boost::any_cast<int>(arg);
                        std::cout << " | Int value: " << value << std::endl;
                } else if(arg.type() == typeid(std::string)) {
                        std::string value = boost::any_cast<std::string>(arg);
                        std::cout << " | String value: " << value << std::endl;
                }
                // ... same for other types such as float
        }
        return 0;
}

int main() {
        Testing({1, 2});
        Testing({std::string("abc"), 1});
        return 0;
}

As you see, you can use typeid to check for the type of the argument and std::initializer_list to allow arbitrary numbers of arguments. 如您所见,可以使用typeid来检查参数的类型,并可以使用std::initializer_list允许任意数量的参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM