C++:组合私有全局变量和模板

C++: Combining private global variables and templates

本文关键字:全局变量 组合 C++      更新时间:2023-10-16

假设翻译单元中有一个全局变量。它是常量,但不是编译时常量(它使用具有非constexpr构造函数的对象初始化)。它被声明为static,因为它应该是翻译单元私有的。显然,该全局是在.cpp文件中定义的。但是,现在我已经向该文件中添加了一个需要全局变量的方法模板。由于它是其他翻译单元将使用的方法,因此必须将其放入标题中。但是,一旦它进入标头,它就无法再访问全局变量。解决此问题的最佳实践是什么?

有,但有点棘手的方法来实现你的目标:

  1. 该变量是私有的,仅对某些元素可用。
  2. 函数模板可以访问它。

在标头中定义的类中使用私有静态变量,并使函数/类模板成为此类的好友。

你的文件.h

class PrivateYourFileEntities {
private:
   static const int SomeVariable;
   // ... other variables and functions
   template <class T>
   friend class A;
   template <class T>
   friend void func();
   // the rest of friends follows
};
template <class T>
void A<T>::func() {
     int a = PrivateYourFileEntities::SomeVariable;
}
template <class T>
void func() {
     int a = PrivateYourFileEntities::SomeVariable;
}

您的文件.cpp

const int PrivateYourFileEntities::SomeVariable = 7;

将方法声明放入 .h 文件中,将方法主体放入.cpp文件中,如下所示:

.h 文件:

#include <iostream>
void myfunc1();
void myfunc2();

.cpp文件:

#include "myheader.h"
static int myglobalvar=90;
    void myfunc1()
    {
      cout << myglobalvar << endl;
    }
    void myfunc2()
    {
      cout << "Oh yeah" << endl;
    }