template <class T>
class Class<T>
{
public:
//functions and other members...
private:
class InnerClass
{
public:
staticconst InnerClass variable;
private:
InnerClass();
//more stuff
}
//rest of outer class
};
Now, outside of the class I am trying to define the value of the const variable
inside InnerClass.
Doesn't work...Can I initialize a static const variable with the default constructor of a class if it is private? Am I just writing my statement wrong?
I thought Template Code needs to always be done inline? Why would my initialization need to be in a .cpp file if everything else can be done inline in my header?
struct Foo {
staticconstint Number = 5; // Compiles just fine
staticconst std::string String = "Hello World"; // Compile error... can't initialize in declaration
};
I'm guessing it has to do with the compiler needing to generate code to initialize the static in
the string case (ie, run a constructor), and putting it in a header is problematic since the compiler
will want to generate that code for every .cpp file that #includes the header.
The whole idea with this line is that you're instantiating variable. The reason this doesn't work is because the above is a template, which doesn't instantiate anything.
Since Class<int> is different from Class<float> -- this means that each of those classes have their own 'variable'. The only way the compiler could really fullfill the above statement is to create an infinite number of 'variable's, one for each T. This, of course, is impossible.
What I suspected you could do, was instantiate a specific variable for T. Something like the following.
However I get errors even when I try that -- and I'm not sure why because it seems logical to me. In any event that's not much of a solution unless you want to restrict how many types of T there can be.
well I would say that variable is const so you cannot modify it outside of the bit of the class constructor that is run during the instantiation of the class. also since your default constructor is private you cannot instantiate
1 2
template<class T>
Class<T>::InnerClass
unless you create a specific constructor and even then you could only instantiate InnerClass when you called that specific constructor.
That's my take at least..
Does InnerClass have to be templated? Right now, according to the declaration in the original post
it is, but nothing there shows that it has to be. Can you simply move InnerClass out of OuterClass?
That would solve the problem....