c++ - 具有可变参数的虚方法

标签 c++ c++11 variadic-templates f-bounded-polymorphism

我正在尝试实现一个在定位器服务(以 this guide 的样式)之后抽象的日志系统,以便日志系统可以针对各种不同的日志情况进行子类化。我更希望能够使用 printf 样式格式字符串而不是 <<,但这意味着支持可变数量的参数。 Variadic 模板可以很容易地解决这个问题,但是,它们不能是虚拟的,这意味着基本日志记录类不能是抽象的(作为接口(interface))。

理想情况下,我需要的是某种方式让父方法不被模板化,而只是接受一个参数包,它将转发给正确的(模板化的)子方法。我主要看到了两种方法,一种是使用 va_list,这显然是不安全的、复杂的,而且并不是真的想轻松地与可变参数模板交互,还有 CRTP,它可以工作,但意味着不能声明抽象的指针在不知道子类类型的情况下定位器对象中的基类,这违背了目的。

这里是假设虚拟模板是一个东西的示例代码:

class Logger
{
    public:
        template <typename ... Args>
        virtual void print(char *filename, int line, std::string &&msg, Args&& ... args) = 0;

    protected:
        template <typename ... Args>
        std::string format(char *filename, int line, std::string &msg, Args&& ... args)
        {
            std::string output = "%s at line %i: " + msg;
            int size = std::snprintf(nullptr, 0, output.c_str());
            // +1 for null termination
            std::vector<char> buf(size + 1);
            std::snprintf(&buf[0], buf.size(), output.c_str(), filename, line, args...);
            return std::string(&buf[0]);
        }


};

class PrintLogger : public Logger
{
    public:
        template <typename ... Args>
        void print(char *filename, int line, std::string &&msg, Args&& ... args)
        {
            std::cout << format(filename, line, msg, args...);
        }
};

这里是 CRTP 解决方案的示例代码(它破坏了定位器):

template <typename Loggertype>
class Logger
{
    public:
        template <typename ... Args>
        void print(char *filename, int line, std::string &&msg, Args&& ... args)
        {
            Loggertype::print(filename, line, msg, args...);
        }

    protected:
        template <typename ... Args>
        std::string format(char *filename, int line, std::string &msg, Args&& ... args)
        {
            std::string output = "%s at line %i: " + msg;
            int size = std::snprintf(nullptr, 0, output.c_str());
            // +1 for null termination
            std::vector<char> buf(size + 1);
            std::snprintf(&buf[0], buf.size(), output.c_str(), filename, line, args...);
            return std::string(&buf[0]);
        }


};

class PrintLogger : public Logger<PrintLogger>
{
    public:
        template <typename ... Args>
        void print(char *filename, int line, std::string &&msg, Args&& ... args)
        {
            std::cout << format(filename, line, msg, args...);
        }
};

这是定位器:

class Global {
    public:
        static void initialize() { logger = nullptr; }
        static Logger& logging()
        {
            if (logger == nullptr)
            {
                throw new std::runtime_error("Attempt to log something before a logging instance was created!");
            }
            return *logger;
        }
        static void provide_logging(Logger *new_logger) { logger = new_logger; }
    private:
        static Logger *logger;
};

最佳答案

你必须处理 2 个问题:

  1. 迭代打包参数
  2. 使用模板参数调用虚函数。

您需要的第一个问题是通过递归函数处理 第二个我与 boost::any

一起使用
class Logger
{
public:


    template <typename ... Args>
    std::string print(Args&& ... args)
    {
        start_format();
        interate_on(args...);
        return end_format();
    }
protected:



    template <typename Arg>
    void interate_on(Arg&& arg)
    {
        print(arg);
    }


    template <typename Arg, typename ... Args>
    void interate_on(Arg&& arg, Args&& ... args)
    {
        print(arg);
        interate_on(std::forward<Args>(args)...);
    }

    virtual void start_format() = 0;

    virtual std::string end_format() = 0;

    virtual void print(boost::any& value) = 0;
};

class PrinterLogger : public Logger
{
protected:
    virtual void start_format()
    {

    }

    virtual std::string end_format()
    {
        return std::string();
    }

    virtual void print(boost::any& value)
    {
        // accumulate printf

    }
};

关于c++ - 具有可变参数的虚方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43130641/

相关文章:

c++ - 使用变量定义数组的大小

c++ - 为什么 clang++ 会对内联的 enable_if 发出警告,然后无法链接?

c++ - 如何对 C++ 可变参数模板进行递归?

c++ - 将任意数量的迭代器对折叠到一个新的迭代器中。元编程以获得良好的语法?

c++ - 根据运行时类型实例化构造函数

c++ - 更正 Visual C++ __FILE__ 宏的大小写

c++ - 错误 C2059 : syntax error : ',' - for macro 'getcwd'

c++ - 将字符串传递给类并保存到 eeprom

c++ - 警告 : Multiple copy constructors defined while deleting them

c++ - move 语义 - 它是关于什么的?