[英]Error C2451 using boost::any
class A {
public:
void f()
{
cout << "A()" << endl;
}
};
class B {
public:
void f()
{
cout << "B()" << endl;
}
};
class C {
public:
void f()
{
cout << "C()" << endl;
}
};
void print(boost::any& a)
{
if(A* pA = boost::any_cast<A>(&a))
{
pA->f();
}
else if(B* pB = boost::any_cast<B>(&a))
{
pB->f();
}
else if(C* pC = boost::any_cast<C>(&a))
{
pC->f();
}
else if(string s = boost::any_cast<string>(a))
{
cout << s << endl;
}
else if(int i = boost::any_cast<int>(a))
{
cout << i << endl;
}
}
int main()
{
vector<boost::any> v;
v.push_back(A());
v.push_back(B());
v.push_back(C());
v.push_back(string("Hello boy"));
v.push_back(24);
for_each(v.begin(), v.end(), print);
}
使用Visual Studio 2010测试字符串时,在print()中出现此错误:
error C2451: conditional expression of type 'std::string' is illegal
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
else if(string s = boost::any_cast<string>(a))
这条线给您造成问题。 字符串s不是指针,它是一个堆栈变量。 您不能检查null。
您可以检查以下整数的原因是整数隐式映射到bool。
0->假
1-> TRUE
您不应在此处的引用上使用any_cast
,因为如果类型不正确,它将引发bad_any_cast
异常。 在后两种情况下使用指针,就像前三种情况一样:
else if(string* s = boost::any_cast<string*>(&a))
{
cout << *s << endl;
}
else if(int* i = boost::any_cast<int*>(&a))
{
cout << *i << endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.