考虑以下非法 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/