VS 2022 17.4.4: Doing some refresh on 2 year old source, certain templates, now, indicate a lot of errors.
This simple template below was just to avoid typing:
std::cout << std::format(..)
by replacing by a simple:
fcout(..)
template<typename ...TArgs>
void fcout(const char* sFormat, TArgs&&... args)
{
std::cout << std::format(sFormat, args...);
}
void test_fcout(void)
{
double x = 10, y = 20, z = x*y;
fcout("{} = {}; L={}, l={}", "Surface", z, x, y);
fcout("{}", "Test");
}
Errors indicated:
error C7595: 'std::_Basic_format_string<char,const char (&)[5]>::_Basic_format_string': call to immediate function is not a constant expression
message : failure was caused by a read of a variable outside its lifetime
message : see usage of 'sFormat'
message : see reference to function template instantiation 'void fcout<const char(&)[5]>(const char *,const char (&)[5])' being compiled
I spent hours to fix it, but never succeed. What did I wrong ? Thanks.
CodePudding user response:
Per the std::format doc on cppreference.com:
As of P2216R3, it is an error if the format string is not a constant expression.
std::vformat
can be used in this case.
P2216R3 was implemented in Visual Studio 2022 v17.2.
So, try this instead:
template<typename ...TArgs>
void fcout(std::string_view sFormat, TArgs&&... args)
{
std::cout << std::vformat(sFormat, std::make_format_args(args...));
}