【问题标题】:How to use BOOST_MPL_ASSERT如何使用 BOOST_MPL_ASSERT
【发布时间】:2024-04-17 15:55:01
【问题描述】:

为什么下面的代码编译失败:

#include <boost/type_traits/is_same.hpp>
#include <boost/mpl/assert.hpp>
#include <string>

int main()
{
    BOOST_MPL_ASSERT(( boost::mpl::is_same<std::string, std::string> ));
    return 0;
}

我收到 C++11 和 C++14 的错误:

In file included from 2:0:
 In function 'int main()':
7:5: error: expected primary-expression before 'enum'

我知道这可能很愚蠢,比如缺少分号。错误信息肯定没有帮助。

【问题讨论】:

    标签: c++ c++11 boost static-assert


    【解决方案1】:

    我同意错误消息绝对没有帮助。

    问题是您将类型特征放在错误的命名空间中。不是boost::mpl::is_same,是boost::is_same

    BOOST_MPL_ASSERT(( boost::is_same<std::string, std::string> ));
    

    您可以通过尝试减少问题来发现这一点,方法是:

    using T = boost::mpl::is_same<std::string, std::string>;
    

    这给出了一个更有用的错误:

    foo.cxx: In function ‘int main()’:
    foo.cxx:10:15: error: expected type-specifier
         using T = boost::mpl::is_same<std::string, std::string>;
                   ^
    

    如果您已经在使用 C++11,那么确实没有太多理由更喜欢 BOOST_MPL_ASSERT 而不是 static_assert。当然,您必须自己写出::type::value 部分,但您可以编写自定义消息,它实际上是语言的一部分。

    另外在这种情况下,错误信息更有帮助:

    foo.cxx: In function ‘int main()’:
    foo.cxx:10:19: error: ‘is_same’ is not a member of ‘boost::mpl’
         static_assert(boost::mpl::is_same<std::string, std::string>::type::value, "!");
                       ^
    

    【讨论】:

    • 这是一个很好的答案。不仅是我真正要求的,还有我下一步需要知道的一切。再次感谢您!