**我有一些建议可以使我的函数成为纯通用的,这会起作用,但我更愿意将函数限制为仅接受 Base 及其子级。
在创建一个可以接受可变参数模板类基类型参数的函数时遇到问题,而该函数实际上将使用派生自 Base 的类调用。我已经尝试了几件事。这是一般的想法。鉴于:
template<typename... Args> struct Base {
std::tuple<Args...> data;
... //other stuff
};
struct DerivedA : Base<string, int> {
};
struct DerviedB : Base<bool, string, int> {
};
创建执行此操作的函数的正确方法是什么:
string moosh_together(Base A, Base B) { //I only need access to Base's members
return get<0>(A.data) + get<1>(B.data);
}
main() {
DerivedA aThing;
get<0>(aThing.data) = "foo";
DerivedB bThing;
get<1>(bThing.data) = "bar'd";
cout << moosh_together(aThing, bThing) << endl;
}
输出:
foobar'd
我尝试了一些 moosh_together 函数的变体,但都不起作用。保持上述状态会生成有关缺少模板参数的编译器错误。我不确定如何将定义 DerivedA 和 DerivedB 的模板参数传递给函数。
我尝试过的其他方法(shot弹枪方法):
string moosh_together(Base<> A, Base<> B) {}
//err: conversion from 'DerivedA' to non-scalar type 'Base<>' requested
template<Base<typename... Args> T1, Base<typename... Args> T2>
string moosh_together(T1 A, T2 B) {}
//err: expected paramter pack before '...'
template<Base<Args...> T1, Base<Args...> T2>
string moosh_together(T1 A, T2 B) {}
//err: 'Args' was not declared in this scope