c++ - 有没有办法决定模板类的模板参数类型?

标签 c++ templates

我有两个模板类,它们的参数由软件的不同层决定。 我必须在下层使用的类是

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/

相关文章:

c++ - 如何获取通过与 libcurl 的连接传输的总字节数?

c++ - 会有标准类型列表吗?

c++ - 模板参数推导和表达式规则

c++ - c++,将enable_if与现有模板类一起使用?

c++ - 在编译时将类型转换为整数?

javascript - Polymer - 遍历模板中的对象

c++ - 从ubuntu上的utc时间计算unix时间

c++ - 命名空间嵌套函数的最佳实践和语义以及extern "C"的使用

c++ - 在没有邻接表或邻接矩阵的情况下 boost 图形设计

c++ - Eclipse C/C++ 控制台行为异常