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

时间:2012-09-20 17:37:30

标签: c++ templates global-variables

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

2 个答案:

答案 0 :(得分:1)

实现目标有一点棘手的方法:

  1. 该变量是私有的,仅适用于某些元素。
  2. 您的功能模板可以访问它。
  3. 在header中定义的类中使用私有静态变量,并使您的函数/类模板成为此类的朋友。

    <强> YourFile.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;
    }
    

    <强> YourFile.cpp

    const int PrivateYourFileEntities::SomeVariable = 7;
    

答案 1 :(得分:-1)

将方法声明放入.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;
    }