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;

 

原文链接: https://www.cnblogs.com/thomas76/p/8528225.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    C++ inline variable

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/397588

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月11日 上午9:16
下一篇 2023年4月11日 上午9:16

相关推荐