Click here to Skip to main content
15,867,704 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Greetings Kind Regards
I am attempting to utilize C++ std::format and pass the format string by name. However this results in compile error as shown below. I have a very long format string and do not wish to stick it in the call site. I do not understand why a format string can not be referenced by name w/o error. Kindly advise why this is so or perhaps how am utilizing incorrectly. Thank You Kindly
C++
import std.core;
using namespace std;

const string _format = "{}";

int main()
{
    std::cout << "Hello World!\n";

	cout << format("{}", 159) << endl;
	// how to utilize format string by name?
	// line below will not compile
	// bugyCode.cpp(18, 17) : error C7595 : 'std::basic_format_string<char,int>::basic_format_string' : call to immediate function is not a constant expression
	// D:\a\_work\1\s\binaries\x86ret\inc\xstring(2302, 29) : message: failure was caused by non - constant arguments or reference to a non - constant symbol
	// D:\a\_work\1\s\binaries\x86ret\inc\xstring(2302, 29) : message: see usage of '_format'
	// bugyCode.cpp(18, 9) : error C2143 : syntax error : missing ';' before ':'
	// bugyCode.cpp(18, 9) : error C2059 : syntax error : ':'
	cout << format(_format, 357) << endl:
}

Solution Found as example below
C++
constexpr auto _format = "{}";


What I have tried:

Read re/ std::format on various sites. No examples were by name nor found any explanation why must be.
Posted
Updated 13-Nov-22 2:22am
v2
Comments
Member 15627495 13-Nov-22 2:43am    
format("{0} mask {1} value {2} build ",value_0,value_1,value_2);


the format parameter is a "prepare the string" option.
Member 15627495 13-Nov-22 2:45am    
when you're lost, in your ide VS, select a keyword, then push F1.
your browser will pop with the help online from microsoft, with a relevant help to read.
Richard MacCutchan 13-Nov-22 8:34am    
Glad you found the answer; see also the comments in my updated solution.

1 solution

The format string must be a constant expression, see std::format - cppreference.com[^].

[edit]
I have been looking at the documentation (per the above link), and trying some tests. Even using the string:
C++
const char* fmt = "{}";

produces the same errors, so it would appear that the template only accepts an actual string constant as the format string.

[/edit]
 
Share this answer
 
v2
Comments
BernardIE5317 13-Nov-22 8:19am    
Thank You for directing me to the page. I read it too quickly prior and found the reference you cite. After some experimentation a solution was found as shown in re-write of question. Thanks Again!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900