Let’s consider a code example like this (it is just an artificial example to combine define and template, don’t look for any sense it it):
#define COMMA ,
template <typename A> class Test
{
public:
Test(){}
void Foo(A var COMMA int test);
};
Test<int> Knarz;
Question:
Is my assumption correct that, first the preprocessor will search/replace all occurrences of COMMA and second the compiler will instantiate any templates in that order?
Followup:
If the above answer is ‘yes‘, as I hope it to be, can you explain why this solution using templates and defines works?
The preprocessor is run before the compiling itself is done, so your assumption that the preprocessor will replace
COMMAbefore the template is instantiated is correct.For your followup:
The solution has little to do with templates. The problem there is that the preprocessor will take commas inside the braces to be argument separators for the macro, since it doesn’t parse the C++ code to see that it is the separator for the template arguments. So the
COMMAmacro is used to insert the,for separating template arguments only after theMOCK_CONSTANT_METHOD0has been substituted. I am however not sure if this is guaranteed to work, since I don’t know the guarantees for the order of macro-substitution by memory. IfCOMMAwould be substituted beforeMOCK_CONSTANT_METHOD0everything falls apart and the code once again doesn’t compile.Edit: After looking into the standard I think the solution should generally work, since the preprocessor will find
MOCK_CONSTANT_METHOD0first and replace it. Only then will it examine the result of the replacement to find theCOMMAmacro. No guarantees though.