可变参数函数并复制粘贴这些参数(就像我们在宏中所做的那样)
Variadic function and copy pasting these parameters (like we can in a macro)
我想要一个可变函数并将这些参数复制粘贴到代码中,就像在宏中一样。在宏中,我们只需将 __VA_ARGS__
放在我们希望复制粘贴的位置。
实际上,我希望这些参数是变量的值,然后将其放入对象声明中(使用这些值调用构造函数)。
看:
struct Object {
std::string name;
int id;
Object(std::string name, int id) {
this->name = name;
this->id = id;
}
};
void create(...) {
Object object(VA_ARGS);
}
int main() {
create("Object1", 1);
}
当然,在这段代码中没有任何事情发生,因为对象超出了范围,但这只是为了说明我的意思。
有什么办法吗?
在 C++ 中执行此操作的正确方法是使用 variadic templates,这是一种允许您操作参数包的语言结构。例如
template <typename... Ts>
Object createObject(Ts&&... xs)
{
return Object{std::forward<Ts>(xs)...};
}
createObject(1, 'a'); // as if `Object{1, 'a'}`
我想要一个可变函数并将这些参数复制粘贴到代码中,就像在宏中一样。在宏中,我们只需将 __VA_ARGS__
放在我们希望复制粘贴的位置。
实际上,我希望这些参数是变量的值,然后将其放入对象声明中(使用这些值调用构造函数)。
看:
struct Object {
std::string name;
int id;
Object(std::string name, int id) {
this->name = name;
this->id = id;
}
};
void create(...) {
Object object(VA_ARGS);
}
int main() {
create("Object1", 1);
}
当然,在这段代码中没有任何事情发生,因为对象超出了范围,但这只是为了说明我的意思。
有什么办法吗?
在 C++ 中执行此操作的正确方法是使用 variadic templates,这是一种允许您操作参数包的语言结构。例如
template <typename... Ts>
Object createObject(Ts&&... xs)
{
return Object{std::forward<Ts>(xs)...};
}
createObject(1, 'a'); // as if `Object{1, 'a'}`