我想在parametrise()辅助函数中定义一系列全局变量,如下所示:
// helper.h
namespace settings {
extern const unsigned short something;
}
namespace helper {
void parametrise(int, char**); // parametrise from command line using boost::program_options
}
// main.cpp
int main( int argc, char** argv) {
helper::parametrise(argc, argv);
return 0;
}
// helper.cpp
void helper::parametrise(int, char**) {
// parse input here
const unsigned short settings::something = .. // this is what I want to do
}
这个代码当然不能编译,但是必须有一种解决方法..或者不是?
答案 0 :(得分:4)
你可以只在那个翻译单元中使它成为可写的,并使它外部为const,如下所示:
// helper.h
namespace settings {
extern const unsigned short& something;
}
void parametrise(int, char**);
// helper.cpp
namespace { namespace settings_internal {
unsigned short something;
}}
namespace settings {
const unsigned short& something = settings_internal::something;
}
void parametrise(int, char**) { settings_internal::something = 123; }