Passing a template which requires a comma to a single-argument macro

▼魔方 西西 提交于 2019-12-04 10:55:10

This should perhaps ideally be a comment, but SO doesn't support code in comments, so, you can do

#include <map>

#define T_ARGS( ... ) < __VA_ARGS__ >

#define FOO( a )  a x;

auto main() -> int
{
    FOO( std::map T_ARGS( int, int ) );
    (void) x;
}

or you can define a macro that resolves to comma, or you can use just about any scheme that's specific to some particular use case (e.g., passing template name separately).

Shafik Yaghmour

The comma is being treated as a macro argument seperator, it does not do this with commas within parenthesizes.

If you are using Boost, they provide BOOST_PP_COMMA:

#include <boost/preprocessor/punctuation/comma.hpp>

#define FOO(a)
FOO(std::map<int BOOST_PP_COMMA int>);

You can also define your own:

#define COMMA ,
FOO(std::map<int COMMA int>);

The preprocessor will only treat unparenthesised commas as a macro argument separator. So what you can do is rewrite std::map<int, int> into something that has parentheses around it. A simple one might be decltype(std::map<int, int>()).

Just add an extra set of parentheses:

#define FOO(a)
FOO((std::map<int, int>));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!