[英]Call a method of a static member for initialization in C++
我有一個具有靜態成員對象的類。 初始化該靜態對象意味着將其某些參數設置為特定值。 但這是通過該對象的函數完成的。 如果它是靜態的,我不知道該怎么辦。 有什么幫助嗎?
更具體地說,我每個類都有一個靜態的Boost logger對象。 它具有ClasName
屬性,並通過add_attribute("ClassName", boost::log::attributes::constant<std::string>("MyClass"))
函數將其設置為name_of_the_class
值。 初始化靜態記錄器的最佳方法是什么? 我已經做好了:
typedef boost::log::sources::severity_logger< severity_levels > BoostLogger;
class MyClass
{
private:
static BoostLogger m_logger;
public:
MyClass()
{
MyClass::m_logger.add_attribute("ClassName", boost::log::attributes::constant<std::string>("MyClass"));
}
}
BoostLogger MyClass::m_logger; // And here I cannot call the add_attribute() function
我知道每次實例化該類時都會這樣做,所以:最好的方法是什么?
您可以一次初始化記錄器,例如在構造函數中使用靜態變量:
MyClass()
{
static bool logger_initialised = false;
if (!logger_initialised)
{
MyClass::m_logger.add_attribute("ClassName", boost::log::attributes::constant<std::string>("MyClass"));
logger_initialised = true;
}
}
請注意,這不是線程安全的。 但是,如果不使用線程,它將起作用,並且記錄器將被初始化一次,但MyClass
是必須實例化MyClass
。
如果BoostLogger
不提供BoostLogger
的構造函數, add_attribute
可以add_attribute
創建自己的函數,例如:
class MyClass
{
private:
static BoostLogger m_logger;
};
BoostLogger CreateBoostLoggerWithClassName(const std::string& className)
{
BoostLogger logger;
logger.add_attribute(
"ClassName",
boost::log::attributes::constant<std::string>(className));
return logger;
}
BoostLogger MyClass::m_logger = CreateBoostLoggerWithClassName("MyClass");
這是您的代碼的更正版本。
MyClass.h:
class MyClass
{
private:
static BoostLogger m_logger; /* This is declaration, not definition.
You need also define the member somewhere */
public:
MyClass() /* So far as this is constructor, it may be called more than once,
I think adding new static function will be better */
{
// MyClass::m_logger.add_attribute("ClassName", boost::log::attributes::constant<std::string>("MyClass"));
// AddAttribute("ClassName"); Uncomment this line if you're really need to add attribute in constructor
}
static void AddAttribute(std::string name) /* this function has been added as advice,
if you're going add attributes as you
did in question,
remove function, and uncomment first line in the constructor */
{
MyClass::m_logger.add_attribute(name, boost::log::attributes::constant<std::string>("MyClass"));
}
}
MyClass.cpp:
BoostLogger MyClass::m_logger = BoostLogger(); // This is definition of static member item
使其不再是add_attribute
調用,而是使您可以使用其構造函數完全初始化BoostLogger
。 然后在定義時只需提供必要的參數即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.