Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create string according to the parameter pack arguments count

I have a function with a parameter pack, I pass this pack to the fmt::format function, and I want to create a formatStr according to the args count, meaning add "{}#" for each passed argument.

I can do it using iterating, but is it possible to do this with one line solution? How to do it gracefully?

    template <typename... Args>
    void formatArgs( Args&&...args)
    {
        const auto size = sizeof...(Args);
        std::string formatStr = ...// "{}#{}#{}..." - {}# should depend on args count
        
        /* 
        std::ostringstream formatStr;
        for (const auto& p : { args... })
            formatStr << {}#";
        */
    
        auto res = fmt::format(formatStr.c_str(), args...);
        ...
    }
like image 790
Alexandr Derkach Avatar asked Apr 07 '26 06:04

Alexandr Derkach


1 Answers

An ugly fold expression would work. It's only redeeming quality is that it's just one line, and in C++20 it should be a constexpr, so in C++20 this'll wind up to be a single std::string constructor call:

#include <string>
#include <iostream>

template<typename ...Args>
std::string string_from_args(Args && ...args)
{
    return std::string{ ((args, std::string{"%s#"}) + ...) };
}

int main()
{
    std::cout << string_from_args(1, 2, 3, 4) << "\n";

    return 0;
}
like image 58
Sam Varshavchik Avatar answered Apr 09 '26 18:04

Sam Varshavchik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!