Home > Net >  How do I declare a member variable within the constructor that doesn't have a predefined type?
How do I declare a member variable within the constructor that doesn't have a predefined type?

Time:01-12

I'm trying to declare a member variable of a class with a type that isn't defined during compilation. I read this article where C 17 fixed template constructors by just redacting the type paramater for a template constructor call. (I probably read it wrong because i'm getting errors.)

class theClass {
    template <typename UDEF> theClass(UDEF var) : memberVar(var) {}
    auto memberVar{ NULL };
};



int main() {
    int number = 3;
    theClass the(number); // Something something C  17
}


Does anybody have any workarounds? Maybe the new operator? This confuses me a lot. I'm getting super generic errors:

Error (active)  E0330   "theClass::theClass(UDEF var) [with UDEF=int]" (declared at line 4) is inaccessible ConsoleApplication1```
Error (active)  E1598   'auto' is not allowed here  ConsoleApplication1

EDIT: I tried putting the template at the initializer list as such: template <typename UDEF> theClass(UDEF var) : UDEF memberVar(var) {} And didn't get any IntelliSense errors, but i'm afraid it won't compile.. It's an initializer list after all, not a declaration list, right? And the odd constructor template call thingy still gives an error.

CodePudding user response:

The template should be on the class, to have a member use the template parameter:

template <typename UDEF>
class theClass {
    UDEF memberVar {};
public:
    theClass(UDEF var) : memberVar(var) {}
};

Now your main can create an object like that:

int main() {
    int number = 3;
    theClass the(number); // CTAD, C  17
}
  •  Tags:  
  • Related