【问题标题】:Storing multiple types and returning single type on request存储多种类型并根据请求返回单一类型
【发布时间】:2017-03-25 22:28:18
【问题描述】:

我需要创建一个存储多个用户定义类型的类。它应该根据需要返回其中之一。有没有办法实现一个函数来返回所有类型?

请注意:我不能使用 Boost 库。我需要在 Visual Studio 中实现

class One {};
class Two {};
class Three {};

enum Type
{
  OneType,
  TwoType,
  ThreeType
};
class GenericType
{
  template <typename T>  // --- How to implement this function
  T getValue(Type type)
  {
     switch(type)
     {
       case One: return oneType;  // Error
       case Two: return twoType;
       case Three: return threeType;
     }
  }
  shared_ptr<OneType> oneType;
  shared_ptr<TwoType> twoType;
  shared_ptr<ThreeType> threeType; 
  Type m_type;
};

【问题讨论】:

    标签: c++ templates types type-conversion


    【解决方案1】:

    在 C++11 中,您有一个 std::tuple 类来完成这项工作。您可以使用std::get 检索所需的元素,如下所示:

    // Create a tuple
    std::tuple<std::shared_ptr<OneType>, std::shared_ptr<TwoType>> tuple{null, null};
    // Get element
    std::get<std::shared_ptr<OneType>>(tuple)
    

    【讨论】:

    • std::get() 只能获取索引的项目(作为参数提供)
    【解决方案2】:

    这份声明,

    template <typename T>  // --- How to implement this function
    T getValue(Type type)
    

    … 其中Typeenum,使参数的运行时选择决定函数结果类型的编译时选择,或者要求参数值的运行时选择与输入。

    前者时间倒退,所以没开,后者傻了。

    如果一个普通的函数模板适合你,那么解决方案很简单:为每个相关类型专门化它。

    如果您需要运行时选择,则改为使用常见的结果包装器类型。对于值语义,它可以是具有union 成员的类,即可区分联合。对于引用语义,它可以是指向可能结果类型的公共基类的指针。

    【讨论】:

    • 对不起,我不太明白。通用结果包装器类型是什么意思。你是说 std::tuple 吗?
    • @Neo:就像boost::variant。由于您无法使用 Boost,因此您必须自己动手。因此提出了实施建议。 std::tuple 不是任何事情的解决方案,因为它只是暴露了成员:如果你可以暴露成员,就没有问题需要解决,这对于客户端代码来说已经足够了。
    猜你喜欢
    • 2016-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    相关资源
    最近更新 更多