I am trying to make the following code work:
#include <string>
#include <tuple>
#include <print>
template<char Specifier>
struct ParseSpecifier;
template<>
struct ParseSpecifier<'s'>
{
static void parse()
{
std::println("string");
}
};
template<>
struct ParseSpecifier<'i'>
{
static void parse()
{
std::println("integer");
}
};
template<std::size_t Index>
void parse_format(const std::string_view format)
{
if (Index == format.size())
return;
ParseSpecifier<format[Index]>::parse();
parse_format<Index + 1>(format);
}
int main()
{
parse_format<0>("iiisss");
}
I know there exist libraries (like fmt) that can compile time validate format strings so this must be possible somehow. I should note, the ultimate goal is not to print “string” and “integer”, but rather to create a std::tuple based on the i
and s
s in the provided string. The string will always be known at compile time.
I am starting small as I am only just learning template metaprogramming. How can I make code like this work? I understand format is not constexpr as function parameters cannot be. Additionally, std::string_view cannot be a template parameter. If I use template<char... Chars>
then I have to call the function like parse_format<0, 'i', 's', 's', 'i', 's'>();
, which is horrible.
Is there any way I can get my attempted code to function? If not, what is the best strategy for compile time validation of strings?
Important note, the final function will be called with one compile time known parameter and one real time parameter (much like fmt::format).
Easy edit: https://godbolt.org/z/s8eoYarja