英文:
Can I assign the template type name dynamically?
问题
以下是你要翻译的代码部分:
// 定义类型和其参数
struct Argument
{
char* name;
int age;
double height;
}
struct typeAndArg
{
QWidget *instance;
Argument args;
}
template<class T>
createPerson(Argument arg)
{
// 一个可以执行类似操作的API,只有类型名T不同,参数也可以根据不同的类型指定
....
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()); // <-- 我只想在这里使用一行代码,让我决定传递给API的类型和参数
}
}
希望这有所帮助。如果你需要进一步的解释或有其他问题,请随时提问。
英文:
//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
答案1
得分: 4
使用可变模板和折叠表达式:
#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);
}
这是您提供的代码,已经按原样呈现。
英文:
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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论