C++ inline variable

考虑一个程序库的设计者,发明了一个Kath类。在Kath.h:

struct Kath
{
    static int const hi;
};

static成员变量需要在某个编译单元(以后简称为cpp)中定义。在Kath.cpp:

int const Kath::hi = 0;   

在两个地方处理同一个事物,这是非常不爽的。特别是对程序库的设计者,如果希望提供只有头文件的一套库(类似STL),就面对更大的麻烦。

有一些workaround技术,解决这个问题。如: 

template< class Dummy >
struct Kath_
{
    static int const hi;
};

template< class Dummy >
int const Kath_<Dummy>::hi = 0;

using Kath = Kath_<void>;

利用模板的成员必须在头文件中定义的规则。还有:

struct Kath
{
    inline int hi() {
        static int const hi=0;
        return hi;
    }
};

利用内联函数,只能在头文件中定义的规则。或者C++17 的便利语法如下:

struct Kath
{
    static const int hi;
};

inline int const Kath::hi = 0;

 

posted @ 2018-03-08 14:18  thomas76  阅读(483)  评论(0)    收藏  举报