I'm working with WinAPI's CreateDialogIndirect function, which has some requirements on the DLGTEMPLATE and DLGTEMPLATEEX structures pointed to by the second parameter. My code works well, however, I would like to get rid of the #define macros.
I created a simplified example to focus on the macros. This is a working program with macros, it can be compiled, and outputs what is expected:
#include <iostream>
int wmain()
{
#define TITLE L"Title"
struct {
wchar_t title[ sizeof( TITLE ) / sizeof( TITLE[ 0 ] ) ];
int font_size;
} s = {
TITLE,
12,
};
std::wcout
<< L"s.title = " << s.title << std::endl
<< L"s.font_size = " << s.font_size << std::endl;
return 0;
}
In Visual Studio 2022, I see three dots at the #define macro, and I can read the following tooltip:
- Macro can be converted to constexpr
- Show potential fixes
- Convert macro to constexpr
I would like to see it converted to something to avoid macros, so I click on it, and the code is changed to this:
#include <iostream>
int wmain()
{
constexpr auto TITLE = L"Title";
struct {
wchar_t title[ sizeof( TITLE ) / sizeof( TITLE[ 0 ] ) ];
int font_size;
} s = {
TITLE,
12,
};
std::wcout
<< L"s.title = " << s.title << std::endl
<< L"s.font_size = " << s.font_size << std::endl;
return 0;
}
If I hit F7 to compile, I get the following error message:
- example.cpp(10,9): error C2440: 'initializing': cannot convert from 'const wchar_t *const ' to 'wchar_t'
I would not like to enter L"Title" two times, and I would not like to calculate the length of the string manually. So, what can be a good substitute for the macro, which is capable of both initializing the struct and determining the size of the array in the struct?