c++ va_list function overload

837 views Asked by At

I currently have 2 function overloads:

void log(const char* format, ...);
void log(const string& message);

and I want that in case of this call: log("hello"); the string version will be called, or in other words the first overload should only be called in case of 2 arguments or more.

I thought about doing this:

template<typename T>
void log(const char* format, T first, ...);

but in this case I will have trouble using va_list properly in the code.

Is there any other solution I might be missing?

EDIT: I thought about checking the size of va_list from inside the function, and redirecting in case of 0, but as far as I understood it's impossible to get the size of va_list.

2

There are 2 answers

3
edmz On BEST ANSWER
  1. Force type construction: log(std::string{"hello}). But this isn't really what you seem to want.
  2. In either of the functions, call the other one.

    void log(const string& s)  
    {
          log(s.c_str());      
    }
    

    But it's not very efficient because you'll have a useless string object, although the compiler may be able to inline the call.

  3. Use variadic templates and SFINAE:

    void log(const string&);
    auto log(const char *ptr, Args&& ... args) -> 
         typename std::enable_if<sizeof...(Args) != 0, void>::type 
    

    The second overload will be available in the set of candidate functions only if there're trailing arguments. Showcase. In C++14, you can use the short-hand version of std::enable_if, std::enable_if_t, which makes the syntax clearer:

    auto log(const char *ptr, Args&& ... args) -> std::enable_if_t<sizeof...(Args) != 0, void>
    

    You can still simplify it in C++11 by using

    template <bool B, typename T>
    using enable_if_t = typename std::enable_if<B, T>::type;
    

If you're calling a function which accepts a va_list (such as printf) you're still able to expand the pack of parameters:

std::printf(ptr, args...);

but not vice versa.

0
AudioBubble On

You might omit the 'printf' function style and use a stream manipulator (taking a variable number of arguments (variadic template)):

// Header
// ============================================================================

#include <iostream>
#include <sstream>
#include <tuple>

// Format
// ============================================================================

namespace Detail {

    template<unsigned I, unsigned N>
    struct Format;

    template<unsigned N>
    struct Format<N, N> {
        template<typename... Args>
        static void write(std::ostream&, const std::tuple<Args...>&, std::size_t offset)
        {}
    };

    template<unsigned I, unsigned N>
    struct Format {
        template<typename... Args>
        static void write(
            std::ostream& stream,
            const std::tuple<Args...>& values,
            std::size_t offset)
        {
            if(offset == 0) stream << std::get<I>(values);
            else Format<I+1, N>::write(stream, values, offset - 1);
        }
    };

    class FormatParser
    {
        public:
        const char* fmt;
        const std::size_t size;

        FormatParser(const char* fmt, std::size_t size)
        : fmt(fmt), size(size)
        {}

        virtual ~FormatParser() {}

        void write(std::ostream& stream) const;

        protected:
        virtual void write_value(std::ostream&, std::size_t index) const = 0;
    };

} // namespace Detail

template<typename... Args>
class Format : public Detail::FormatParser
{
    public:
    typedef std::tuple<const Args&...> Tuple;
    static constexpr std::size_t Size = std::tuple_size<Tuple>::value;

    const std::tuple<const Args&...> values;

    Format(const char* fmt, const Args&... values)
    : Detail::FormatParser(fmt, Size), values(values...)
    {}

    protected:
    void write_value(std::ostream& stream, std::size_t index) const {
        Detail::Format<0, Size>::write(stream, values, index);
    }
};

template <typename... Args>
inline Format<Args...> format(const char* fmt, const Args&... values) {
    return Format<Args...>(fmt, values...);
}

template <typename... Args>
inline std::ostream& operator << (std::ostream& stream, const Format<Args...>& format) {
    format.write(stream);
    return stream;
}

template <typename... Args>
inline std::string format_string(const char* fmt, const Args&... values) {
    std::ostringstream result;
    result << format(fmt, values...);
    return result.str();
}

// Source
// ============================================================================

#include <cctype>
#include <cstdlib>
#include <stdexcept>

namespace Detail {

    void FormatParser::write(std::ostream& stream) const {
        const char* s = fmt;
        while(*s) {
            switch(*s) {
                case '{':
                if(*(++s) != '{') {
                    char* end;
                    unsigned long index = std::strtoul(s, &end, 10);
                    while(*end != '}') {
                        if( ! std::isspace(*end)) {
                            s = end;
                            if( ! *s) s = "End";
                            throw std::runtime_error(std::string(
                                "Invalid Format String `") + fmt + "` at " + s);
                        }
                        ++end;
                    }
                    s = end + 1;
                    if(index < size) write_value(stream, index);
                    else throw std::runtime_error(std::string(
                        "Invalid Format Index `")  + std::to_string(index)
                        + "` in `" + fmt + '`');
                    continue;
                }
                break;

                case '}':
                if(*(++s) !=  '}') {
                    if( ! *s) s = "End";
                    throw std::runtime_error(
                        std::string("Invalid Format String `") + fmt + "`"
                        "Missing `}` at " + s);
                }
                break;
            }
            stream.put(*s++);
        }
    }
} // namespace Detail


// Usage
// ============================================================================

int main() {
    // a = 1; b = 2; 1 + 2 = 3
    std::cout << format("a = {0}; b = {1}; {0} + {1} = {2}", 1, 2, 3) << "\n";
}

Also: Have a look at boost::format