仅使用宏在标头中定义静态变量

Define a static variable in header only using macro

本文关键字:定义 静态 变量      更新时间:2023-10-16

我的目标是能够仅在标头中创建一个静态变量,该宏将负责在.cpp文件中使用我提供的值对其进行初始化。它应该看起来像这样:

struct UserDefaults {
STATIC(bool, isFullscreen, true)
STATIC(bool, isBorderless, false)
STATIC(std::string, profileName, "") 
}

这将等于:

// .hpp file
struct UserDefaults {
static bool isFullscreen;
static bool isBorderless;
static std::string profileName;
}
// .cpp file
bool UserDefaults::isFullscreen = true;
bool UserDefaults::isBorderless= false;
std::string UserDefaults::profileName = "";

我已经看过如何在仅标题库中拥有静态数据成员?,但我无法将 Pesche 的解决方案应用于我的情况。

#include <iostream>
#define STATIC(type, name, value) 
static type& name() { static type ret = value; return ret; }
struct UserDefaults
{
STATIC(bool, isFullscreen, true)
STATIC(bool, isBorderless, false)
STATIC(std::string, profileName, "")
};
int main()
{
UserDefaults ud;
std::cout << ud.isFullscreen() << " " << ud.isBorderless() << " " << ud.profileName() << std::endl;
}

输出

1 0 

为什么要使用宏?这就是 c++。

#include <string>
#include <iostream>
template<class Type, Type(*init)()>
struct static_thing
{
using value_type = Type;
operator value_type&() const {
return get();
}
static value_type& get() {
static value_type _ { init() };
return _;
}
/*
* add whatever operations you need
*/
template<class Source>
value_type& operator=(Source&& value) {
get() = std::forward<Source>(value);
}
friend auto operator<<(std::ostream& os, static_thing const& st) -> std::ostream&
{
return os << st.get();
}
};
inline bool make_true() { return true; }
inline bool make_false() { return true; }
inline std::string empty_string() { return std::string(); }

struct UserDefaults
{
static_thing<bool, make_true> isFullscreen;
static_thing<bool, make_false> isBorderless;
static_thing<std::string, empty_string> profileName;
};

int main()
{
auto defs = UserDefaults();
defs.profileName = "foo";
std::cout << defs.profileName << " " << defs.isFullscreen << std::endl;
}