Search code examples
c++variablesglobal-variablesscoped

How to make a scoped variable global in C++?


I am working on a large project and require to make a scoped variable global so it can be accessed throughout the whole class.

A simple scenario of where this might be used is to make the integer x global.

class a
{
public:
    a()
    {
        int x;
    }

    void print()
    {
        std::cout << x << std::endl;
    }
}

A more complex scenario may include making FunctionTypeClass<FunctionType> FunctionTypeDataStore:

class thread
{
public:
    template<typename FunctionType>
    thread(FunctionType* function)
    {
        FunctionTypeClass<FunctionType> FunctionTypeDataStore;
    }

    FunctionTypeClass get_function_type()
    {
        return FunctionTypeDataStore;
    }


    ~thread()
    {
    }

    template<typename StoreFunctionTypeTemp>
    class FunctionTypeClass
    {
        StoreFunctionTypeTemp Variable;
    }
}

Solution

  • Make a member variable out of it and your class templated, not the constructor:

    template<typename FunctionType>
    class thread
    {
    private:
        template<typename StoreFunctionTypeTemp>
        class FunctionTypeClass
        {
            StoreFunctionTypeTemp Variable;
        };
    
        FunctionTypeClass<FunctionType> FunctionTypeDataStore;
    public:
    
        thread(FunctionType* function) { }
    
        FunctionTypeClass<FunctionType> get_function_type()
        {
            return FunctionTypeDataStore;
        }
    };