lundi 11 janvier 2021

Get ordinal number of C++ variadic template parameter

I want to retrieve index of each parameter from variadic template parameters, currently I am using this approach:

template<unsigned Index, typename T>
void bind(T t){
    // use Index to bind T here
}

template<unsigned Index, typename T, typename ...Args>
void bind(T t, Args...args){
    bind<Index>(t);
    bind<Index+1>(args...);
}

template <typename ... Args>
void bind_all(Args...args){
    constexpr int Index = 0;
    bind<Index>(args ...);
}

Usage:

bind_all(1,1.24f, 3.14, "Hello", std::string{"World"}, true);

My question: Is there a better way to achieve this, to get ordinal numbers of variadic template parameters?

Edit: I want to use this implementation to wrap sql prepared statement and to bind specific parameter to specific index. Here is an example of code that I want to wrap, instead of listing each bind individually, I want to call bind_all

    prepare(statement, "insert into tab (a, b) values (?, ?);");
    const int eight_int = 8;
    statement.bind(0, &eight_int);
    const string eight_str = "eight";
    statement.bind(1, eight_str.c_str());
    execute(statement);

Aucun commentaire:

Enregistrer un commentaire