Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/142.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++函数对象参数_C++_Object_Arguments - Fatal编程技术网

C++函数对象参数

C++函数对象参数,c++,object,arguments,C++,Object,Arguments,如何让函数接受任意数量的参数,然后相应地检查其数据类型? 我理解java中的对象…参数然后做数据检查,但是C++中的 基本上类似于将其转换为C++ public int Testing(String sql, Object...arguments) throws SQLException{ PreparedStatement ps = con.prepareStatement(sql); for(int i=0; i< arguments.length; i++){

如何让函数接受任意数量的参数,然后相应地检查其数据类型? 我理解java中的对象…参数然后做数据检查,但是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();
}

虽然您可以使用可变模板或类似的东西,但我建议只使用变量库,如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;
}

如您所见,您可以使用typeid检查参数的类型,并使用std::initializer\u list允许任意数量的参数。

我不太确定您到底想要什么,特别是因为Java的instanceof不接受可变数量的参数,所以类比就不成立了。@Konrad Rudolph like我将实际使用for循环来检查每个参数的数据type@Tyra如何检查?用它做什么?一个所需用法的代码示例将非常有用。谢谢!很抱歉再次麻烦,但如何将它设置在PraveReDebug中?这取决于C++中使用的库连接到SQL Server。有很多可用的,比如soci、Qt或默认的mysql-c++-conctor。如果你能提出一个新问题并提供这些信息,那将是最好的。