Hello all,
I have a problem with regards instantiating global constant value.
I know at most of the time the following code works:
In header.h file:
1 2 3 4
|
#ifndef _HEADER_
#define _HEADER_
extern const int a;
#endif
|
In header.cpp file:
const int a = 5;
And in main.cpp file:
1 2 3 4
|
#include "header.h"
int main(void){
int b = a;
}
|
However, I encounter a problem which involves templates, and now the header file looks like:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
#ifndef _HEADER_
#define _HEADER_
extern const int a;
template <typename T>
void somefunction_1(){
... some action with T ...
someclass<a>(); # a class taking "a" as a "template" parameter
somefunction<a>(); # a function taking "a" as a "template" parameter
}
#endif
|
and "main.cpp" is:
1 2 3 4
|
#include "header.h"
int main(void){
somefunction_1<int>();
}
|
The "someclass" and "somefunction" are well defined taking the value of "a" as template parameters (or whatever name of parameters) that MUST be instantiated as constant at compiling.
Then the problem arises:
If I follow the usual way, the compiler won't SEE the value of "a" at compiling "main.cpp", since "a" is instantiated when compiling the file "header.cpp".
If I declare the value a at .h file: " const int a = 5 ;" there will be a problem of multi-definition at linking when other files use the "header.h".
My current solution is assigning the value of a at both declaring stage and instantiating stage; that is:
In header.h file:
1 2 3 4 5 6 7
|
#ifndef _HEADER_
#define _HEADER_
extern const int a = 5 ;
....
#endif
|
And in header.cpp file:
const int a = 5;
This passes the compiling and linking by g++ version 4.8.5.
As I'm not confident with this solution, I come for help to see if anyone would give me any suggestions or comments to this problem.
Thanks a lot first!
All the best!
BTW, I have no idea why the formatting scripts do not work on my screen. I tested with two different computers and two different browsers, neither of them worked. Sorry if the format puzzles you.
Edit: Thanks to Ganado, now I can format my thread.