将模板参数传递给宏的方法

时间:2021-11-28 23:17:43

I am unable to use Google Test's ASSERT_THROW() macro in combination with multiple template arguments. Consider that I want to make sure that construction of Matrix<5,1> throws:

我无法将Google Test的ASSERT_THROW()宏与多个模板参数结合使用。考虑一下,我想确保Matrix <5,1>的构造抛出:

ASSERT_THROW(Matrix<5,1>(), std::runtime_error);

(this example doesn't make a lot of sense, of course this shoud not throw, but it is what stayed after simplifying what I had.)

(这个例子没有多大意义,当然这不应该抛出,但它是在简化我所拥有的东西之后留下的。)

I get this output from MS VC++ 2008:

我从MS VC ++ 2008获得此输出:

warning C4002: too many actual parameters for macro 'ASSERT_THROW'
error C2143: syntax error : missing ',' before ';'

Whereas there are no problems with:

虽然没有问题:

ASSERT_THROW(Matrix<1>(), std::runtime_error);

How can I overcome this problem?

我怎样才能克服这个问题?

Thanks!

3 个解决方案

#1


18  

the problem is the extra comma, you will need to protect it from the macro. Try

问题是额外的逗号,你需要保护它免受宏。尝试

ASSERT_THROW((Matrix<5,1>()), std::runtime_error);

#2


17  

#define COMMA ,
ASSERT_THROW(Matrix<5 COMMA 1>(), std::runtime_error);

Edit: @tletnes answer is simpler, however this one will work even if the macro parameter used as a non-expression. For example:

编辑:@tletnes答案更简单,但即使宏参数用作非表达式,这个也会起作用。例如:

BOOST_FOREACH(std::pair<int COMMA int>& v, myVec) { } // works
BOOST_FOREACH((std::pair<int, int>)& v, myVec) { } // fails

More edit: The macro COMMA is already defined in boost:

更多编辑:宏COMMA已在boost中定义:

#include <boost/preprocessor/punctuation/comma.hpp>
ASSERT_THROW(Matrix<5 BOOST_PP_COMMA() 1>(), std::runtime_error);
BOOST_FOREACH(std::pair<int BOOST_PP_COMMA() int>& v, myVec) { }

#3


7  

#define COMMA , may not compile in GCC. Use #define COMMA() , instead. Why can't I add comment to other's post?

#define COMMA,可能无法在GCC中编译。请改用#define COMMA()。为什么我不能在其他帖子上添加评论?

#1


18  

the problem is the extra comma, you will need to protect it from the macro. Try

问题是额外的逗号,你需要保护它免受宏。尝试

ASSERT_THROW((Matrix<5,1>()), std::runtime_error);

#2


17  

#define COMMA ,
ASSERT_THROW(Matrix<5 COMMA 1>(), std::runtime_error);

Edit: @tletnes answer is simpler, however this one will work even if the macro parameter used as a non-expression. For example:

编辑:@tletnes答案更简单,但即使宏参数用作非表达式,这个也会起作用。例如:

BOOST_FOREACH(std::pair<int COMMA int>& v, myVec) { } // works
BOOST_FOREACH((std::pair<int, int>)& v, myVec) { } // fails

More edit: The macro COMMA is already defined in boost:

更多编辑:宏COMMA已在boost中定义:

#include <boost/preprocessor/punctuation/comma.hpp>
ASSERT_THROW(Matrix<5 BOOST_PP_COMMA() 1>(), std::runtime_error);
BOOST_FOREACH(std::pair<int BOOST_PP_COMMA() int>& v, myVec) { }

#3


7  

#define COMMA , may not compile in GCC. Use #define COMMA() , instead. Why can't I add comment to other's post?

#define COMMA,可能无法在GCC中编译。请改用#define COMMA()。为什么我不能在其他帖子上添加评论?