我有两个模板类,它们的参数由软件的不同层决定。 我必须在下层使用的类是
template <class RoutineInfoId,
class ErrorInfoId,
class LoadBarInfoId>
class InformCBSet
我必须在上层使用的类是
template <class LanguageId,
class RoutineInfoId,
class ErrorInfoId,
class LoadBarInfoId>
class Info
我还可以创建“信息”类
template <class LanguageId,
class SomeInformCBSet>
鉴于
typedef InformCBSet<SomeRoutineInfoId,
SomeErrorInfoId,
SomeLoadBarInfoId> SomeInformCBSet
我想通过直接使用 SomeInfoCBSet 作为“信息类”的模板参数从上层的 SomeInfoCBSet 中获取(这是下层类的类型)。
有什么办法可以实现吗? 谢谢
最佳答案
你可以使用这个或类似的东西:
template<typename T> struct InformCBSetTypes;
template<typename T0, typename T1, typename T2>
struct InformCBSetTypes<InformCBSet<T0, T1, T2> > {
typedef T0 RoutineInfoId;
typedef T1 ErrorInfoId;
typedef T2 LoadBarInfoId;
};
能够使用typename InformCBSetTypes<SomeInformCBSet>::RoutineInfoId
等在你的Info
类模板。出于演示目的:
#include <iostream>
#include <string>
template<typename T0, typename T1, typename T2>
struct InformCBSet { };
template<typename T> struct InformCBSetTypes;
template<typename T0, typename T1, typename T2>
struct InformCBSetTypes<InformCBSet<T0, T1, T2> > {
typedef T0 RoutineInfoId;
typedef T1 ErrorInfoId;
typedef T2 LoadBarInfoId;
};
int main() {
typedef InformCBSet<int, double, std::string> MySet;
// Note: To use these inside a template, you'll have to write "typename"
// before them (as with all typedefs in dependent types) so that the
// compiler knows to expect a type before it knows which specialization
// of InformCBSetTypes it's ultimately going to use.
InformCBSetTypes<MySet>::RoutineInfoId i = 1; // int
InformCBSetTypes<MySet>::ErrorInfoId d = 2.3; // double
InformCBSetTypes<MySet>::LoadBarInfoId s = "Hello, world!"; // string
std::cout << i << ", " << d << ", " << s << std::endl;
}
关于c++ - 有没有办法决定模板类的模板参数类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28070981/