我想为参数包使用一个使用别名,这样模板就可以在代码库的其他地方使用。在下面的代码中,我注释了我要使用类型的行。
template <typename FirstArg, typename ... OtherArgs>
struct Base {
using UsableFirstArg = FirstArg;
// this would be needed later
// using UsableOtherArgs... = OtherArgs...;
virtual OtherClass method(OtherArgs... a) = 0
};
template <typename DerivedOfBaseInstantiation>
struct CallerStructure {
// to be used here
// OtherClass unknownCall(typename DerivedOfBaseInstantiation::UsableOtherArgs... args) {
// DerivedOfBaseInstantiation instance;
// return instance.method(args...);
// }
}
在写代码的时候 CallerStructure
的论点。unknownCall
是不知道的,是由实例化的 CallerStructure
哪儿 DerivedOfBaseInstantiation
的类型,是由 Base
. 在一个更完整的例子中,应该是这样的。
class OtherClass {
};
template <typename FirstArg, typename ... OtherArgs>
struct Base {
using UsableFirstArg = FirstArg;
using UsableOtherArgs... = OtherArgs...;
virtual OtherClass method(OtherArgs... a) = 0;
};
struct Derived_df : Base<int, double, float> {
OtherClass someMethod(Base::UsableFirstArg); // int
OtherClass method(double, float) override ;
};
template <typename DerivedOfBaseInstantiation>
struct CallerStructure {
OtherClass knownCall(typename DerivedOfBaseInstantiation::UsableFirstArg a) {
DerivedOfBaseInstantiation instance;
return instance.someMethod(a);
}
OtherClass unknownCall(typename DerivedOfBaseInstantiation::UsableOtherArgs... args) {
DerivedOfBaseInstantiation instance;
return instance.method(args...);
}
};
void instantiations() {
CallerStructure<Derived_df> c;
[[maybe_unused]] auto a = c.knownCall(42);
[[maybe_unused]] auto b = c.unknownCall(23., 11.f);
}
有什么提示可以告诉我们如何访问变量模板 Base
中的方法接口的方法。CallerStructure
?
你不能对变量模板参数进行别名。你可以把它们包在 std::tuple
:
template <typename FirstArg, typename ... OtherArgs>
struct Base {
using UsableFirstArg = FirstArg;
using UsableOtherArgs = std::tuple<OtherArgs...>;
virtual OtherClass method(OtherArgs... a) = 0;
};
拆包需要一些帮手
template <typename DerivedOfBaseInstantiation,
typename = typename DerivedOfBaseInstantiation::UsableOtherArgs>
struct CallerStructure;
template <typename DerivedOfBaseInstantiation, typename ... OtherArgs>
struct CallerStructure<DerivedOfBaseInstantiation, std::tuple<OthersArgs...>> {
OtherClass knownCall(typename DerivedOfBaseInstantiation::UsableFirstArg a) {
DerivedOfBaseInstantiation instance;
return instance.someMethod(a);
}
OtherClass unknownCall(OtherArgs... args) {
DerivedOfBaseInstantiation instance;
return instance.method(args...);
}
};