c++11 variadic templates and std::endl

A simpler option to achieve the same goal:

// global or class member
enum MyEndl { my_endl };

// class member function
void log(MyEndl x) { std::cout << std::endl; }

usage:

log.log("Nazdar ", "bazar ", "cau", my_endl, "kik");

I came up with this, basically re-defining std::endl via a custom wrapper my_endl taking default template parameters. Not the most elegant, but it does the job. Of course, for more such manipulators, one should write a specialized wrapper, but I guess even this can somehow be possible by a more clever implementation.

#include <iostream>
#include <string>
#include <type_traits>

class Logger {

public:

    template<typename T>
    void log(T val);

    template <typename T, typename ...Args>
    void log(T val, Args... args);
};

template<typename T>
void Logger::log(T val) {
    std::cout << val;
}

template<typename T, typename ...Args>
void Logger::log(T val, Args... args) {

    log(val);
    log(args...);

}

template< class CharT = char, class Traits = std::char_traits<CharT> >
inline std::basic_ostream<CharT, Traits>& my_endl( std::basic_ostream<CharT, Traits>& os )
{
    return std::endl(os);
} 

// or, use the excellent (and better) suggestion by 0x499..., 
// auto manip = std::endl<char, std::char_traits<char>>; 
// log.log(..., manip)


int main(int argc, char* argv[])
{
    Logger log;

    // log.log("Nazdar ", "bazar ", "cau", std::endl, "kik"); // ERROR: cannot determine which instance of function template "std::endl" is intended
    log.log("Nazdar ", "bazar ", "cau", my_endl<>, "kik");

    std::cin.get();

    return 0;
}

Tags:

C++

C++11