【问题标题】:Error C2451 using boost::any使用 boost::any 时出现错误 C2451
【发布时间】:2011-04-05 16:58:52
【问题描述】:
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

【问题讨论】:

    标签: c++ boost boost-any


    【解决方案1】:
    else if(string s = boost::any_cast<string>(a))
    

    这条线给你带来了问题。 string s 不是指针,它是堆栈变量。您不能检查 null。

    您可以检查下面的整数的原因是整数隐式映射到 bool。
    0 -> 错误
    1 -> 是的

    【讨论】:

      【解决方案2】:

      您不应该在此处的引用上使用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;
      }
      

      【讨论】:

        猜你喜欢
        • 2017-08-11
        • 2014-09-03
        • 1970-01-01
        • 2015-08-27
        • 2021-04-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多