Question

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?

Was it helpful?

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();

OTHER TIPS

If you know the type statically when you create the instance, you should use C++ templates and make the type a template parameter.

If you know it only dynamically (i.e. based on user input), you can either branch then and instantiate the template with different type parameters, or you can go for a completely dynamical solution (like boost::any or equivalent).

However, I believe that if you can't do this with templates then there's something wrong in your program design. The idea of C++ static typing is that types are known at compile time. Normally in object-oriented design you would use polymorphism instead of weak typing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top