2015-09-03 10 views
2

我有以下5個文件:global_vars.h,global_vars.cpp content.h content.cpp main.cpp。如何使用C++ extern常量變量作爲不同文件中的模板參數

global_vars.h

#ifndef global_vars_h 
#define global_vars_h 

namespace Constants{ 

    extern const unsigned int b; 

} 

#endif 

global_vars.cpp

#include "global_vars.h" 

namespace Constants{ 

    extern const unsigned int b(5); 


} 

content.h

#ifndef CONTENT_H_ 
#define CONTENT_H_ 

#include "global_vars.h" 
#include <bitset> 

struct a{ 

    std::bitset<Constants::b> s; 
    int a=10; 

}; 

#endif 

content.cpp

#include "content.h" 

a xVar; 

的main.cpp

#include "content.h" 
int main(){ 
    return 0; 
} 

我收到以下錯誤:

In file included from content.cpp:1:0: 
content.h:11:31: error: the value of ‘Constants::b’ is not usable in a constant expression 

In file included from content.h:4:0, 
from content.cpp:1: 
global_vars.h:6:28: note: ‘Constants::b’ was not initialized with a constant expression 
extern const unsigned int b; 

我必須使用常量:: B比content.cpp其他文件/ .H(其它位集),以及使我怎麼能這樣做呢?感謝幫助。

謝謝

+0

global_vars.cpp中不應該有關鍵字「extern」。它阻止編譯器在二進制global_vars.o中創建變量。你會得到一個鏈接錯誤,說這個變量是未定義的。 – iksess

回答

2

你問的是不可能的。

在C++中,模板完全由編譯器解析,鏈接器只能看到完全實例化的模板類和函數體。編譯器只能看到給定編譯單元中的代碼。

因此,即使intextern const並且在某個編譯單元中賦予一個值(使其在運行時有效),它也不可能用作任何其他編譯單元中的模板參數。在解決哪個模板實例引用相同類型的時候,編譯器無法知道該值是否爲int

最接近你可能最有可能的是,你可以指向那個int作爲模板參數,然後如果你有,一個使用在運行時運行的模板參數的函數,它可以取消引用指針以獲取常量值。如果你啓用了鏈接時優化,它甚至可能將其內聯,但我不確定。

+0

我可以在global_vars.h中使用#define來規避它嗎? – user2105632

+0

當然,如果有一個全局包含文件,你甚至可以像'struct my_constants {static constexpr int my_int = 42; };'我認爲,這可能比宏觀更好 –