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

大憨熊 提交于 2020-01-06 15:17:51

问题


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?


回答1:


@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.




回答2:


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?



来源:https://stackoverflow.com/questions/4904821/how-to-define-a-global-variable-template-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!