c++ - 将类型 T 的多态包装器转换为类型 U?

标签 c++ templates types c++11 polymorphism

考虑以下非法 C++11 代码背后的意图:

struct Base
{
    template<typename U>
    virtual U convert() = 0;
};

template<typename T>
struct Derived : Base
{
    T t;

    template<typename U>
    virtual U convert() { return U(t); }
};

struct Any
{
    Base* b;

    template<typename U>
    operator U() { return b->convert<U>(); }
};

int main()
{
    Any a = ...;
    string s = a; // s = a->b->t if T is convertible to string
                  //    fails otherwise with compile error or runtime exception
                  //                            (either acceptable)
}

有没有办法达到与法典相同或相似的效果?

(仅供引用,上述方式是非法的,因为模板可能不是“虚拟的”)

更新:

struct Base
{
    void* p;
    type_info type;
};

template<typename T>
struct Derived : Base
{
    Derived()
    {
         p = &t; // immovable
         type = typeid(T);
    }

    T t;
};

struct Any
{
    Base* b;

    template<typename T = U, typename U>
    operator U()
    {
        if (b->type != typeid(T))
           throw exception();

        T* t = (T*) b->p;

        return U(*t);
    }
};

最佳答案

这是你想要的吗?

struct Base
{
  virtual void* convert(const std::type_info&) = 0;
};

template<typename T>
struct Derived : Base
{
  virtual void* convert(const std::type_info& ti)
  { return typeid(T) == ti ? &t : nullptr; }

  T t;
};

struct Any
{
  Base* b;

  template<typename U>
    operator U()
    {
      if (auto p = b->convert(typeid(U)))
        return *static_cast<U*>(p);
      throw std::exception();
    }
};

正如其他答案所说,很难确切地知道您想要什么,因为您只显示了无效代码,没有解释您想要实现的目标。

编辑 哦,我现在明白了,您希望它适用于任何可转换类型,而不仅仅是精确匹配...那么不,您不能将 type_info 返回到它表示的类型中,派生类型需要它来测试给定的 type_info 是否对应于其存储类型可转换为的类型。您需要知道正确的类型并通过推导显式或隐式地以某种方式指定它。如果您随后想将其转换为另一种类型,您可以单独进行:

Any a{ new Derived<int>() };
try {
  char c = a;  // throws
}
catch (...)
{
}
int i = a;        // OK
char c = (int)a;  // OK

关于c++ - 将类型 T 的多态包装器转换为类型 U?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14097572/

相关文章:

c++ - 没有范围保护的安全锁定/解锁

C++/R : clang: error: linker command failed with exit code 1 (use -v to see invocation)

c++ - 与字符串一起使用时对函数模板的 undefined reference (GCC)

haskell - 我可以拥有完全多态的函数吗?

c++ - 我将 ASCII 单词转换为数字,但无法解码它们。如何转换 1=a、2=b、28=ab 等? (伪代码好吧)

c++ - *1.0 在这段代码中做了什么?

html - Symfony2 - 渲染模板时获取外部内容

C++ 模板 : When to include template parameters in templatized struct?

Java - DAO 不同类型的相同枚举

javascript - 可以在 Typescript 中输入递归可变参数函数吗?