Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++11 variadic templates and std::endl

Tags:

c++

c++11

I tried to do logger using C++11 variadic templates, but it doesn't work for std::endl, because std::endl is template function and the compilator doesn't know what specialization of std::endl to select. Is there any way how i can force to always select std::endl<char, std::char_traits<char>>? If possible, i want to use directly std::endl.

EDIT: it looks like it is not currently possible with C++11 and and best way is to use #define or what vsoftco answered.

#include <iostream>
#include <string>

class Logger {

public:

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

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

};

// explicit specialization not working 
template<>
void Logger::log(std::basic_ostream<char, std::char_traits<char>> (*modifier) (std::basic_ostream<char, std::char_traits<char>>)) {

    std::cout << modifier;

}

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...);

}

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", std::endl<char, std::char_traits<char>>, "kik");

    std::cin.get();

    return 0;
}
like image 466
Krab Avatar asked Mar 29 '15 00:03

Krab


1 Answers

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");
like image 77
M.M Avatar answered Oct 13 '22 07:10

M.M