如何在C ++中定义一个全局变量模板? [英] How to define a global variable template in C++?

查看:722
本文介绍了如何在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?

推荐答案

@AnonymousCoward

@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;
}

它也可能是一个好主意,为客户端提供工厂函数而不是强制他们使用T的默认初始化器。

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.

这篇关于如何在C ++中定义一个全局变量模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆