2015-09-03 12 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; };'我认为,这可能比宏观更好 –