Search code examples
c++variablesvariable-types

Set variable type for a c++ class variable during instantiation


I have a c++ class such as the following:

class some_class {

    protected:
        decide_later some_variable;

    public:
        void some_random_function();

};

void some_class::some_random_function() {

    decide_later another_variable;

}

The problem is that I don't know what variable type some_variable will be until I create an instance of the class. What I want to do is something like the following:

some_class class_instance(std::string);

And that would set decide_later to use std::string (or int, or double, or whatever it is told to use). In addition, it would be great if I could use decide_later as a variable type later on in other functions that are members of the class. For example, in the function some_random_function().

I have tried using boost::any to do this, but it seems to only work for numeric types. Besides, I think it would be more efficient if I could actually set the actual variable type.

Is this possible?


Solution

  • You are looking for templates. Declare your class like:

    template <typename T> class some_class {
    
        protected:
            T some_variable;
    
        public:
            void some_random_function() {
                T another_variable;
            }
    
    };
    

    and instantiate it with:

    some_class<std::string> class_instance();