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

时间:2017-08-12 17:43:50

标签: c++ c++11 static macros

我的目标是能够在带有宏的标题中创建一个静态变量,该宏将负责在.cpp文件中为我初始化它,并提供值I。看起来应该是这样的:

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 = "";

我看过How to have static data members in a header-only library?,但我无法为我的案例申请Pesche的解决方案。

2 个答案:

答案 0 :(得分:3)

#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 

答案 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;

}