1

翻訳単位にグローバル変数があるとします。これは定数ですが、コンパイル時定数ではありません (非コンストラクタを持つオブジェクトで初期化されますconstexpr)。static翻訳単位に対して非公開にする必要があるため、宣言されています。明らかに、そのグローバルは.cppファイルで定義されています。ただし、グローバル変数を必要とするメソッド テンプレートをそのファイルに追加しました。これは他の翻訳単位で使用されるメソッドであるため、ヘッダーに配置する必要があります。ただし、ヘッダーに入ると、グローバル変数にアクセスできなくなります。この問題を解決するためのベスト プラクティスは何ですか?

4

2 に答える 2

1

目標を達成するための少しトリッキーな方法があります。

  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;
于 2012-09-20T19:46:39.597 に答える
-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;
    }
于 2012-09-20T17:45:22.287 に答える