C++:组合私有全局变量和模板
C++: Combining private global variables and templates
假设翻译单元中有一个全局变量。它是常量,但不是编译时常量(它使用具有非constexpr
构造函数的对象初始化)。它被声明为static
,因为它应该是翻译单元私有的。显然,该全局是在.cpp
文件中定义的。但是,现在我已经向该文件中添加了一个需要全局变量的方法模板。由于它是其他翻译单元将使用的方法,因此必须将其放入标题中。但是,一旦它进入标头,它就无法再访问全局变量。解决此问题的最佳实践是什么?
有,但有点棘手的方法来实现你的目标:
- 该变量是私有的,仅对某些元素可用。
- 函数模板可以访问它。
在标头中定义的类中使用私有静态变量,并使函数/类模板成为此类的好友。
你的文件.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;
}
相关文章:
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 当vector是tje全局变量时,c++中vector的内存管理
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 内联函数中具有内部链接的全局变量
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 全局变量 多读取器 一个写入器多线程安全?
- 如果全局变量默认是外部变量,为什么要添加"extern"关键字?
- 不同作用域中的静态变量和全局变量
- C++ 在编译时具有函数计算全局变量
- 修改程序的入口点时未调用全局变量的构造函数
- 使用 std::ios_base::Init 正确初始化全局变量
- 为什么我的全局变量似乎没有变化?
- C ++程序如何返回我的数组或写入全局变量
- 为什么我的数组值与此处的全局变量不匹配?
- QT C++中对全局变量的未定义引用
- 跨多个类的全局变量而不会出现重定义错误?
- 赋予全局变量而不是局部变量优先级的函数 - (异常行为)
- C++线程不检测全局变量更改
- 在 elf 文件中查找全局变量的位置
- C++:组合私有全局变量和模板