2016-05-03 30 views
-2

我嘗試創建一個調用使用模板的可變參數函數的宏。 我使用下面的代碼,但鏈接不能解析到宏調用...宏和模板中的可變參數函數

此代碼是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(); 
} 

Logger類:

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可解決問題。

代碼工作:

`Logger類:

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); 
+0

您可以顯示'Logger'類的定義? – shrike

+0

我已更新帖子 – Kryx

+0

爲什麼要使用宏而不是函數? – Holt

回答

1

你可能有叫你的宏(和因此logTrace模板函數)在聲明Logger::logTrace()的源文件中,但未定義/實現(例如:在包含Logger.h的源文件中)。 logTrace模板函數的完整定義是您的宏工作所必需的。

我建議你定義logTrace成員函數到Logger類:

class Logger { 

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

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

不錯,它工作正常!我用解決方案編輯帖子,非常感謝 – Kryx