【问题标题】:variadic functions in macro and templates宏和模板中的可变参数函数
【发布时间】:2016-05-03 15:24:00
【问题描述】:

我尝试创建一个宏来调用使用模板的可变参数函数。 我使用以下代码,但链接器无法解析对宏的调用...

此代码是 Logger 类的一部分:

template< typename ... Args >
void Logger::logTrace(Args const& ... args)
{
    std::ostringstream stream;
    using List = int[];
    (void)List{ 0, ((void)(stream << args), 0) ... };
    BOOST_LOG_SEV(log_, trace) << stream.str();
}

记录器类:

class Logger {

public:
    static Logger* getInstance(const char *logFile = "LogClient.log");

    template< typename ... Args >
    void logTrace(Args const& ... args);

private:
    Logger(std::string fileName);   
    virtual ~Logger();

    void initialize(std::string fileName);

    static Logger* logger_; // singleton instance
};

和宏:

#define LOG_TRACE(...) Logger::getInstance()->logTrace(__VA_ARGS__);

调用宏:

LOG_TRACE("A log with a number: %d", 5);

感谢您的帮助!

编辑和解决:

问题与可变参数函数甚至宏无关,而是与链接有关。 在类定义中实现 logTrace 即可解决问题。

代码工作:

`记录器类:

class Logger {

public:
    static Logger* getInstance(const char *logFile = "LogClient.log");

    template< typename ... Args >
    void logTrace(Args const& ... args)
    {
        std::ostringstream stream;
        using List = int[];
        (void)List{ 0, ((void)(stream << args), 0) ... };
        BOOST_LOG_SEV(log_, trace) << stream.str();
    }

private:
    Logger(std::string fileName);   
    virtual ~Logger();

    void initialize(std::string fileName);

    static Logger* logger_; // singleton instance
};

和宏:

#define LOG_TRACE(...) Logger::getInstance()->logTrace(__VA_ARGS__);

调用宏:

LOG_TRACE("A log with a number: %d", 5);

【问题讨论】:

  • 您可以显示Logger 类定义吗?
  • 我已经更新了帖子
  • 为什么要使用宏而不是函数?
  • 错误信息是什么。你能提供一个最小的工作示例吗?
  • 这是错误信息:错误 LNK2019: 无法解析的外部符号“public: void __cdecl dhlogging::Logger::logWarn(char const (&)[44])” (??$logWarn@$$BY0CM@$$CBD@Logger@dhlogging@@QEAEAY0CM@$$CBD@Z) 在函数“public: __cdecl Player::Player(class std::basic_string,class std::allocator,class std::basic_string,class std::allocator,struct Position,class Ogre::相机 *)" (??0Player@@QEAA@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@0UPosition@@PEAVCamera@Ogre@@@Z )

标签: c++ function templates macros variadic


【解决方案1】:

您可能在声明了 Logger::logTrace() 但未定义/实现的源文件中调用了您的宏(因此也调用了 logTrace 模板函数)(例如:在包含 Logger.h 的源文件中)。您的宏需要完整的 logTrace 模板函数定义才能工作。

我建议你在 Logger 类中定义 logTrace 成员函数:

class Logger {

public:
    static Logger* getInstance(const char *logFile = "LogClient.log");

    template< typename ... Args >
    void logTrace(Args const& ... args)
    { /* add implementation here */ }
    ...

【讨论】:

  • 很好,效果很好!我用解决方案编辑帖子,非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-12
  • 1970-01-01
  • 2021-10-01
相关资源
最近更新 更多