0

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();
}
Tyra
  • 105
  • 3
  • 12
  • Possible duplicate of [C++ equivalent of instanceof](http://stackoverflow.com/questions/500493/c-equivalent-of-instanceof) – Piotr Siupa Mar 23 '17 at 11:30
  • I’m not quite sure what exactly you want, especially since Java’s `instanceof` does *not* take a variable number of arguments so the analogy breaks down. – Konrad Rudolph Mar 23 '17 at 11:43
  • @Konrad Rudolph like i'll actually use a for loop to check each parameter's data type – Tyra Mar 23 '17 at 12:04
  • @Tyra Check *how*? To do *what* with it? A code example of the desired usage would be tremendously helpful. – Konrad Rudolph Mar 23 '17 at 12:34

1 Answers1

1

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.

Philipp Ludwig
  • 3,758
  • 3
  • 30
  • 48
  • Thank you! sorry to trouble again but how do i set it in preparedstatements? – Tyra Mar 24 '17 at 09:20
  • That depends on what library you are using in C++ to connect to your SQL server. There are many available, like _soci_, _Qt_ or the default mysql-c++-conector. It would be the best if you could ask a new question and provide this information. – Philipp Ludwig Mar 24 '17 at 09:25