Search code examples
c++templatesstlvariadic-templates

How to invoke c_str() for std::string variadic template parameters?


I have a method that accepts format string + arguments (right as printf()), however, I'm using variadic templates for this purpose:

template<typename... Args>
static void log(const char* pszFmt, Args&&... args)
{
    doSomething(pszFmt, std::forward<Args>(args)...);
}

Some of args can be std::string instances. Is it possible to make sure that doSomething will never accept std::string, but will always accept const char* instead of each source std::string passed to log()?

In other words, I need a way to forward all the args to doSomething() making all the std::string arguments substituted with what std::string::c_str() returns.

Thanks in advance!


Solution

  • You could define your own "forwarding" method:

    template<typename T>
    decltype(auto) myForward(T&& t)
    {
        return t;
    }
    
    template<>
    decltype(auto) myForward(std::string& t)
    {
        return t.c_str();
    }
    
    
    template<>
    decltype(auto) myForward(std::string&& t)
    {
        return t.c_str();
    }
    
    
    template<typename... Args>
    static void log(const char* pszFmt, Args&&... args)
    {
        doSomething(pszFmt, myForward<Args>(std::forward<Args>(args))...);
    }