如何使用BOOST_MPL_ASSERT
How to use BOOST_MPL_ASSERT
为什么以下代码编译失败:
#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'
我知道这可能是一些愚蠢的事情,比如缺少分号。错误消息绝对没有帮助。
我同意错误消息绝对没有帮助。
问题是您将类型特征放在了错误的命名空间中。不是 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, "!");
^
为什么以下代码编译失败:
#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'
我知道这可能是一些愚蠢的事情,比如缺少分号。错误消息绝对没有帮助。
我同意错误消息绝对没有帮助。
问题是您将类型特征放在了错误的命名空间中。不是 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, "!");
^