0

I'm trying to create a pointer of template object using it's constructor:

int num = 10;
templateClass<int>* testPInt = new templateClass<num>;

When i compile the program:

error: the value of `num` is not usable in a constant expression

How do i solve that? i mean the experssion is not constant :/

Stayalive
  • 37
  • 6
  • You can't do this. C++ does not work this way. Template parameters must be constant expressions. – Sam Varshavchik Dec 04 '20 at 03:32
  • I see, so i have to create another const int num2 = num; Then i have to assign it to the template parameter wooh.. – Stayalive Dec 04 '20 at 03:33
  • No, that won't work either. Here, "constant" ***really*** means constant, meaning "known at compile time". Can you tell me what exactly is `num` at compile time? Unless you can give me a specific numerical integer value ***right now***, it is not a constant value for the purposes of it being a template parameter. – Sam Varshavchik Dec 04 '20 at 03:34
  • @SamVarshavchik: That wasn't a proper duplicate. The template is templated on the *type*; they just accidentally passed the value as the template parameter, rather than an argument to the constructor. It's meant to be templated on `int`, not on `10`. – ShadowRanger Dec 04 '20 at 03:35
  • Let's just wait for the OP to clarify. I believe, @ShadowRanger, that this was just a simplified example, and the OP is attempting to provide a non-constant template parameter. If the OP clarifies, and that's what's being asked, then I'll remove the duplicate, that's all. – Sam Varshavchik Dec 04 '20 at 03:36
  • @SamVarshavchik: Maybe? But they're assigning to `templateClass* testPInt` which is properly templated on the type, not the value. Maybe worth closing as a typo (they used `` when they meant `(num)`?). – ShadowRanger Dec 04 '20 at 03:38
  • Or, perhaps, the OP did declare `template class templateClass`, and is attempting to instantiate it for some calculated integer value, but assign the result to a "`templateClass *`", which would also be a fundamental disconnect on how templates work. That would stlil qualify as a dupe for the same reason, ***and*** the fact that `templateClass` would not be an instantiated template type. – Sam Varshavchik Dec 04 '20 at 03:40

1 Answers1

0

Your class is supposed templated on the type (int), not the value (10); your problem is that you're trying to pass the value as the templated type. Just do:

templateClass<int>* testPInt = new templateClass<int>(num); // <-- value passed as argument
                                              // ^^^ type goes here

The type is known at compile-time, and the value is allowed to vary at runtime.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271