c++ - 具有可以是两种类型之一的数据成员的类

标签 c++ class templates variant any

最好用一些代码解释一下:

class MyClass {
  public:
    MyClass(const std::string& d1, const std::string& d2, const std::vector<AorB>& d3) : data1(d1), data2(d2), data3(d3) {}

    std::string getData1();
    std::string getData2();
    std::vector<AorB> getData3();

  private:
    std::string data1;
    std::string data2;
    std::vector<AorB> data3;
}

int main() {
  MyClass myClassA("d1", "d2", std::vector<A>());
  MyClass myClassB("d1", "d2", std::vector<B>());

  A myA = myClassA.getData3();
  B myB = myClassB.getData3();
}

当使用boost变量或boost任何变量时,此工作流“几乎”有效,但是我要避免的事情是调用getData3的结果上的boost::get以获取实际类型。换句话说,我不希望MyClass的使用者必须知道A或B是否存储在data3中。我只希望他们能够调用getData3(),它是创建时传递的任何类型。

我认为可以通过具有模板特化/递归继承的模板来实现,但是我还不太清楚如何使它正常工作。也许看起来像这样?
class MyClass {
  public:
    template <typename AorB>
    MyClass(const std::string& d1, const std::string& d2, const std::vector<AorB>& d3) : data1(d1), data2(d2), data3(d3) {}

    std::string getData1();
    std::string getData2();

    template <typename AorB>
    std::vector<AorB> getData3();

  private:
    std::string data1;
    std::string data2;

    template <typename AorB>
    std::vector<AorB> data3;
  }

  int main() {
    MyClass myClassA<A>("d1", "d2", std::vector<A>());
    MyClass myClassB<B>("d1", "d2", std::vector<B>());

    A myA = myClassA.getData3();
    B myB = myClassB.getData3();
  }

但是,这将不起作用,因为我们不能有非静态模板类成员。

最佳答案

要执行您要尝试的操作,您需要将模板作为一个整体应用于MyClass,例如:

template <typename AorB>
class MyClass {
  public:
    MyClass(const std::string& d1, const std::string& d2, const std::vector<AorB>& d3) : data1(d1), data2(d2), data3(d3) {}

    std::string getData1();
    std::string getData2();
    std::vector<AorB> getData3();

  private:
    std::string data1;
    std::string data2;
    std::vector<AorB> data3;
};

int main() {
  MyClass<A> myClassA("d1", "d2", std::vector<A>());
  MyClass<B> myClassB("d1", "d2", std::vector<B>());

  A myA = myClassA.getData3();
  B myB = myClassB.getData3();
}

关于c++ - 具有可以是两种类型之一的数据成员的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60956976/

相关文章:

c++ - 完全限制对文件夹的所有类型的访问

C# : Converting Base Class to Child Class

php - 将 woocommerce_page_title 存储在变量中并将其显示在 Woocommerce 中

c++ - C++11 类型检查代码的奇怪编译器警告

C++变量重载歧义

c++ - std::tuple 和 boost::tuple 之间的转换

ios - 排序核心数据获取(swift 4)

jQuery - 你能检查一个类是否有另一个类吗?

c++ - 仅匹配某些类型的模板函数?

c++ - 在单元安全代码中处理文字零