I am on a project where I have to use a reference to a constant templated object as a parameter of another object's template.
Simply put I would like to do this:
template<typename T>
class A {...}
template<typename T, A<T>& a>
class B {...}
int main(){
const A<int> a;
B<int, a> b;
Problem is I can't figure out how to make it happen and I need your help.
On visual studio, the above code will produce the following error : "C2971: a variable with non-static storage duration cannot be used as a non-type argument"
If I try to use constexpr
instead of const, with the following changes :
constexpr A<int> &a = A<int>(3);
B<int,a> b;
I get the following error "C2131: expression did not evaluate to a constant"
Well I did try a few things that I saw on other posts regarding similar matters but unfortunately did not find anything that could solve my problem.
I am most certainly doing something wrong but can't figure out what.
Thank you in advance for your help!
EDIT : I tried the answer but unfortunately, even if it seems to be ok at first, I got this error while compiling : C2970 : an expression involving objects with internal linkage cannot be used as a non-type argument. Which appear to suggest that I cannot use the template parameter in another file? (I separated all the classes in different hpp) Any ideas ?
SOLVED: To solve the problem I used the solution hereunder and (I assume because my class was in a separate hpp file) just put the keyword extern
before it to have :
extern const A<int> a;
int main(){ B<int, a> b; }
And it works like a charm.