Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ template functions with variable arguments

Is it possible to write a c++ template function which takes a variable number of input variables of different types (number of input can be limited to say 10)? For example take a function sql_exec() which executes an sql query string and saves the resulting rows in std vectors of the type supplied, i.e.

std::vector<double> x,y;
std::vector<std::string> s;
std::string query="select * from ...";

sql_exec(query, s,x,y); // error if less than 3 rows or conversion not possible

Now my naive approach would have been (limited to max 2 vectors)

struct null_type {};
template <typename T1=null_type, typename T2=null_type>
void sql_query(const std::string& query_str, std::vector<T1>& col1,
           std::vector<T2>& col2) {
    ...
}

Of course that's stupid as I didn't tell the function about default arguments and we get

error: default template arguments may not be used in function templates

but actually it compiles with gcc and -std=c++0x. However, obviously sql_query() still doesn't take variable length input and needs to be called with 2 vectors. Also, I'd like to have something portable working on most of the current compilers. Anything obvious I've overlooked? I know I can change the design and maybe use boost::tuple or something else but I'd have liked such a simple interface.

like image 817
tom Avatar asked Jun 29 '11 15:06

tom


1 Answers

In C++0x this achieved through variadic templates (and the number of arguments can get huge, limit being implementation specific).

In C++03, this is emulated by having preprocessor macros generating lots of template functions of various arity (see Boost.Preprocessor).

I've used the C++03 technic to generate the "bind" from 1 to 10 arguments and it works pretty well.

like image 123
Matthieu M. Avatar answered Sep 18 '22 00:09

Matthieu M.