如何获取基类的模板类型

时间:2018-01-09 04:11:29

标签: c++ templates template-meta-programming

C ++标准或C ++标准库中的哪些内容将实现get_base_template_arg<>在此示例中正在执行的操作?

template <typename TResponse>
class request {};

class request1 : public request<int> {};

class mediator {
 public:
  template <typename TRequest, typename TResponse
     = get_base_template_arg<TRequest>::type>
  TResponse send(TRequest r) { /* ... */ }
};

这样我就可以做到:

mediator m{};
request1 r{};
int x = m.send(r);

修改 谢谢你Brian的回答;完整的解决方案可能如下所示:

template <typename TResponse>
class request {
 public:
  using response_type = TResponse;
};

class request1 : public request<int> {};

class mediator {
 public:
  template<typename TRequest,
    typename TResponse = typename TRequest::response_type>

  TResponse send(const TRequest& r) { /* ... */ }
};


// usage:
mediator m{};
request1 r{};
auto x = m.send(r); // x is inferred `int`

1 个答案:

答案 0 :(得分:6)

将模板参数公开为typedef通常很有用:

template <typename TResponse>
class request {
  public:
    using ResponseType = TResponse;
}

然后,要从TRequest获取所需的类型,您只需编写typename TRequest::ResponseType;成员名称将在基类中找到。