I have a struct defined inside of a template class and I would like to create a std::formatter for that struct to be able to print that struct instances by using std::print.
The class I have:
template <typename ValueType, std::size_t SizeOfEachStack> requires (SizeOfEachStack > 0)
class ThreeStack
{
public:
struct StackProperties
{
std::size_t min_index{0};
std::size_t max_index{0};
std::size_t current_index{0};
};
ThreeStack()
{
for(std::size_t stack_number = 0; stack_number < num_of_stacks; stack_number++)
{
stack_properties.at(stack_number).min_index = stack_number * SizeOfEachStack;
stack_properties.at(stack_number).current_index = stack_properties.at(stack_number).min_index;
stack_properties.at(stack_number).max_index = stack_properties.at(stack_number).min_index + SizeOfEachStack - 1;
}
};
// Print function to print the internal arrays.
void print_internal_arrays()
{
for(std::size_t stack_number = 0; stack_number < num_of_stacks; stack_number++)
{
std::print("Stack {}: {}n", stack_number, stack_properties.at(stack_number));
}
}
private:
static constexpr size_t num_of_stacks{3};
std::array<ThreeStack::StackProperties, num_of_stacks> stack_properties{};
};
And here is the std::formatter I created and which does not work:
// Create a std::formatter for the ThreeStack::StackProperties struct for any ThreeStack<ValueType, SizeOfEachStack>.
template <typename ValueType, std::size_t SizeOfEachStack>
struct std::formatter<ThreeStack<ValueType, SizeOfEachStack>::StackProperties>
{
constexpr auto parse(format_parse_context& ctx) { return ctx.begin(); }
template <typename FormatContext>
auto format(const ThreeStack<ValueType, SizeOfEachStack>::StackProperties& stack_properties, FormatContext& ctx)
{
return format_to(ctx.out(), "min_index: {}, max_index: {}, current_index: {}", stack_properties.min_index, stack_properties.max_index, stack_properties.current_index);
}
};
I got the below compile error for this std::formatter:
<source>:43:78: error: type/value mismatch at argument 1 in template parameter list for 'template<class _Tp, class _CharT> struct std::formatter'
43 | struct std::formatter<ThreeStack<ValueType, SizeOfEachStack>::StackProperties>
| ^
<source>:43:78: note: expected a type, got 'ThreeStack<ValueType, SizeOfEachStack>::StackProperties'
<source>:43:13: error: template class without a name
43 | struct std::formatter<ThreeStack<ValueType, SizeOfEachStack>::StackProperties>
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Compiler returned: 1
https://godbolt.org/z/qeKsMrb4Y