C++ 将T型多态包装器转换为U型?
考虑以下非法C++11代码背后的意图:C++ 将T型多态包装器转换为U型?,c++,templates,types,c++11,polymorphism,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 {
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)
}
根据你的最新情况,我认为这就是你正在努力做的
#include <typeinfo>
#include <exception>
#include <string>
template <typename T>
struct Any{
T* t;
Any():t(NULL){}
Any(const T& _t){
t=new T(_t);
}
template<typename U>
operator U(){
if(typeid(T)!=typeid(U) || t==NULL)
throw std::exception();
return *t;
}
};
int main (){
Any<std::string> a(std::string("Nothing"));
std::string b=a;
return 0;
};
如果这对你没有帮助,请用文字而不是代码来解释你想要达到的目标。告诉我们为什么要使用这两个额外的基类和派生类也是很有用的。这就是你想要的吗
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();
}
};
对于那些觉得这个概念很有趣但对C++03/C++11不太了解的人来说,你能发布编译器错误吗?首先,函数模板在C++03和C++11中都不能是虚拟的。现在,如果它不能是虚拟的,那么如何将U从任何转换函数传播到在任何情况下看起来都是虚拟的基类转换函数。@PlatinumAzure:非法的部分是模板可能不是“虚拟的”不,没有,因为在任何情况下,您都没有源和目标的类型。。。除非您明确指定这些转换,否则您的更新或多或少与boost::any相同。您必须知道获取值所存储的类型,而在原始问题中并非如此。然后您只需将其强制转换为所需的任何类型。请参阅boost::any:。Base与占位符等价,派生与holder等价。
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();
}
};
Any a{ new Derived<int>() };
try {
char c = a; // throws
}
catch (...)
{
}
int i = a; // OK
char c = (int)a; // OK