仅使用宏在标头中定义静态变量
Define a static variable in header only using macro
我的目标是能够仅在标头中创建一个静态变量,该宏将负责在.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;
}
相关文章:
- 如何在C++中定义静态成员结构
- 如何在基类中定义静态接口,并确保该接口必须在派生类中实现
- 仅使用宏在标头中定义静态变量
- C++ dll 定义静态成员
- C++类中定义静态对象
- 如何从具有专用化的类模板定义静态成员变量?
- 为什么必须在C++中定义静态数据成员?
- 通过呼叫constexpr函数来定义静态constexpr成员
- 'class MyClass' 在尝试定义静态结构实例时不会命名类型
- 具有静态模板类成员的模板类:如何定义静态成员
- 定义静态类字段时多个已定义符号的链接器错误
- 为什么在定义静态成员变量时不遵循定义顺序
- 我们可以在构造函数中定义静态类成员吗?
- 无法使用 CMake 变量PROJECT_SOURCE_DIR定义静态库的绝对路径
- 源文件中定义静态原子变量不好
- 如何链接自定义静态库
- 为什么在 linux 信号事件中未定义静态成员的使用
- 在类外部定义静态匿名枚举
- 在类声明中定义静态变量时未解析的外部符号
- 在 main.cpp 以外的文件中定义静态数组