suppose the following code:
#define __INIT_TYPE(type) { template<typename type>struct S{ };}
__INIT_TYPE(int);
int main(){
}
the second line produces the following error
Function definition for '\__INIT_TYPE' not found. Expected a declaration.
Why does it happen? so far as I know the macro has to be replaced with the templated struct and which will be declared and then defined.
If I am just missing something and there is a solution to q.1, is it considered a bad practice to nest types in the program with macros like this?
CodePudding user response:
In C avoid macros for as long as you can they are mostly bad practice. They are type unsafe and in general do not make code more readable (for other people). Just stick to standard C if you can.
In your case __INIT_TYPE is not initializing anything, only creating a template instance of S.
If you want an initialized instance of S Just make a function template that creates your struct.
template<typename type_t>
struct S
{
};
template<typename>
auto make_S()
{
return S<typename type_t>{};
}
int main()
{
auto s = make_S<int>();
}
CodePudding user response:
You defined the macros as a function with the body in braces, like a function body w/o a function name:
#define __INIT_TYPE(type) { template<typename type>struct S{ };}
Braces are not allowed outside functions. You might want
#define __INIT_TYPE(type) template<typename type>struct S{ };
Suggest that you take a look at What are the rules about using an underscore in a C identifier? to avoid further errors.