Tyra
Tyra

Reputation: 105

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++?

basically something like converting this into 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();
}

Upvotes: 0

Views: 66

Answers (1)

Philipp Ludwig
Philipp Ludwig

Reputation: 4192

While you could use variadic templates or something similar, I'd suggest just using a variant library such as boost::variant, keeping it simple:

#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.

Upvotes: 1

Related Questions