SB HK
SB HK

Reputation: 15

Can I assign the template type name dynamically?

//define the type and its argument
struct Argument
{
    char* name;
    int age;
    double height;
}
struct typeAndArg
{
    QWidget *instance;
    Argument args;
}

template<class T>
createPerson(Argument arg)
{
//an API which do similiar case but only the typename T is differnt, the //argument can also be specify according to //differnt type
    ....
    T* w = new T(arg.name,arg.age,arg.height);
    .....
    return w;
};

main()
{
    QMap<QWidget*,Argument> myMap;
    QPushButton a;
    QCheckBox b;
    QLineEdit c;
    
    myMap[&a] = Argument("me", 18, 111.11);
    myMap[&b] = Argument("you", 25, 222.22);
    myMap[&c] = Argument("him", 67, 333.33);

    for(auto iter = myMap.begin();iter != myMap.end(); ++iter){
        createPerson(decltype(iter.key)),iter.value());//<--I just //want to use one line here, let me decide what type and argument to //pass to the API
    }   
}

the key question is here: I want to use a single for loop to do all the things in one line, don't want to specify typename always, because the map maybe very long and random order, I don't want to call the API mutiple times

Upvotes: -1

Views: 150

Answers (1)

HolyBlackCat
HolyBlackCat

Reputation: 96335

Use a variadic template, with a fold expression:

#include <iostream>

template <typename T>
void func(const T &value)
{
    std::cout << __PRETTY_FUNCTION__ << " --> " << value << '\n';
}

template <typename ...P>
void func_for_each(const P &... values)
{
    (func(values), ...);
}

int main()
{
    int a = 1;
    double b = 2.1;
    float c = 3.1f;
    func_for_each(a, b, c);
}

Upvotes: 4

Related Questions