【问题标题】:return nested template member in non template class在非模板类中返回嵌套模板成员
【发布时间】:2015-01-11 13:19:59
【问题描述】:

我想创建一个包含任何类型数据成员的事件类,并使其成为非模板类​​。 但它可以设置内容提供模板类型的内容。 我有使用事件类内容的处理函数。

NewEvent.h 文件

class NewEvent {
public:
  NewEvent(const int64_t& value = 0) : value_(value) {}

  int64_t value() const { return value_; }
  void set_value(const int64_t& value) { value_ = value; }

  class ElementBase {
  public:
    virtual ~ElementBase() {}
    template <typename ContentT> ContentT& content() const;
    template <typename ContentT> void set_content(const ContentT&);
  };

  template <typename ContentT, typename Allocator = std::allocator<ContentT>>
  class Element : public ElementBase {
  public:
    Element(const Allocator& alloc = Allocator()) : alloc_(alloc) {}

    typedef std::allocator_traits<Allocator> AllocatorTraits;

    ContentT& content() const {
      return content_;
    }
    void set_content(const ContentT& content) {
      AllocatorTraits::construct(alloc_, &content_, content);
    }

  protected:
    ContentT content_;
    Allocator alloc_;
  };

  template <typename ContentT>
  void set_content(ContentT& content) {
    ElementBase* element = new Element<ContentT>();
    element->set_content(content);
    content_.reset(element);
  }

  template <typename ContentT>
  ContentT& content() const {
    return content_->content<ContentT>();
  }

private:
  int64_t value_;

  std::unique_ptr<ElementBase> content_;
};

template <typename ContentT>
ContentT& NewEvent::ElementBase::content() const {
  return dynamic_cast<NewEvent::Element<ContentT>&>(*this).content();
}

template <typename ContentT>
void NewEvent::ElementBase::set_content(const ContentT& content) {
  dynamic_cast<NewEvent::Element<ContentT>&>(*this).set_content(content);
}

Main.cpp

struct Data {
    int returns;
};
void print(Data data) {
}
int main() {
    struct Data data;
    // ...
    NewEvent new_event;
    new_event.set_content<Data>(data);

    print(new_event.content());
    return 0;
}

在我的代码中,set_content 函数运行良好。 但我不知道如何接收 content() 并根据内容类型进行调用。 NewEvent 类中的 content() 函数存在编译错误。

错误 C2783:“ContentT &NewEvent::ElementBase::content(void) const”:无法推断“ContentT”的模板参数

如何解决这个推导类型问题,或者有其他方法可以实现吗?

【问题讨论】:

    标签: c++ class templates member


    【解决方案1】:

    在你的函数中:

    template <typename ContentT>
    ContentT& content() const { .. }
    

    ContentT 这里不能推断 - 当你调用它时,你没有提供任何编译器可以用来确定调用哪个版本的content()(因此出现错误)。它怎么知道你想要content&lt;Date&gt;()content&lt;int&gt;() 还是...?您必须像调用 set_content() 时一样在调用站点显式提供类型:

    print(new_event.content<Date>()); // now compiler knows which content() to call.
    

    (请注意,您正在实现的内容实际上与 boost::any 相同,以防您想使用该类型。)

    【讨论】:

      猜你喜欢
      • 2014-02-11
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 2017-01-15
      • 2019-04-12
      • 2020-12-16
      • 1970-01-01
      相关资源
      最近更新 更多