简体   繁体   中英

How to define a global variable template in C++?

Suppose you have to write a template library that operates on a client-supplied type. Also, suppose that this library really needs to access a global variable parameterized by the client-supplied type. How would you go about implementing this pattern?

Here is the solution I use to emulate this behavior:

template <typename T> class Global {
public:    
    static T *pVar;

private:    
    Global() {}
    Global(const Global& rhs) {}
    void operator=(const Global& rhs) {}
};

template <typename T> T* Global<T>::pVar = new T;

It seems to do what I want for my particular application. Is there any problem that restricts its applicability?

@AnonymousCoward

this is derived from your solution. note the initialization/destruction patterns in this variant (read the output if you don't have it memorized already). you can use this to defer creation until access, and to destruct and free at termination (which may be useful for custom types):

#include <iostream>
#include <memory>

class t_custom {
public:
    t_custom() {
        std::cout << "custom ctor: " << __PRETTY_FUNCTION__ << "\n";
    }

    ~t_custom() {
        std::cout << "custom dtor: " << __PRETTY_FUNCTION__ << "\n";
    }
};

template<typename T>
class Global {
public:
    static T* Shared() {
        std::cout << "enter: " << __PRETTY_FUNCTION__ << "\n";
        static std::auto_ptr<T>pVar(new T);
        std::cout << "access: " << __PRETTY_FUNCTION__ << ":\t\t";
        return pVar.get();
    }

private:
    Global();
    ~Global();
    Global(const Global& rhs);
    Global& operator=(const Global& rhs);
};

template<typename T>
class Global_orig {
public:
    static T* const pVar;
private:
    Global_orig();
    Global_orig(const Global_orig& rhs);
    Global_orig& operator=(const Global_orig& rhs);
};

template<typename T>T* const Global_orig<T>::pVar(new T); // << oh no! global construction

int main(int argc, char* const argv[]) {

    std::cout << ">> main: " << __PRETTY_FUNCTION__ << "\n\n";

    std::cout << Global<float>::Shared() << "\n";
    std::cout << Global<int>::Shared() << "\n";
    std::cout << Global<t_custom>::Shared() << "\n";

    std::cout << Global_orig<t_custom>::pVar << "\n";

    std::cout << "\n<< main: " << __PRETTY_FUNCTION__ << "\n\n";

    return 0;
}

it may also be a good idea for the client to supply a factory functor for you, rather than forcing them to use T's default initializer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM