【问题标题】:Different approach to single static variable for a template class模板类的单个静态变量的不同方法
【发布时间】:2010-02-11 19:37:55
【问题描述】:

我从来没有真正需要在模板中使用全局变量(实际上我不太支持这样的设计)但是这个topic 让我很好奇。

即使回答了,它也启发了我尝试不同的方法。我没有使用继承,而是想出了这个:

class Bar {};

class {
private:
    Bar bar;
    template <class T> friend class Foo;
} static foobar_singleton;

template <class T> 
class Foo 
{ 
public:
    static Bar bar() { return foobar_singleton.bar; }
};

对我来说,foobar_singleton 的工作方式类似于“非成员静态私有”,因为它的内容只能由模板类 Foo 访问。尽管我不确定这实际上是一个优势,但它也避免了继承。我的解决方案似乎可以只包含标题,而不需要另一个定义文件。

我想看看对于这种方法的看法,与用作让我好奇的线程答案的方法相比。例如,我想听一些问题的例子:

1. 您在我的示例中看到任何明显的优势吗?或者就此而言,明确的缺点?
2.您是否建议将 bar 属性设为静态成员并将使用的类命名为单例?
3. 这让你们想起了任何设计模式?可能类似于pimpl idiom?
4. 您看到任何编译器可移植性问题吗? (我仅使用 MSVC 和 GCC 对其进行了测试)
5.关于成为可能的仅标头实现是否正确?我实际上并不完全确定静态变量foobar_singleton

提前致谢!

【问题讨论】:

    标签: c++ templates static


    【解决方案1】:

    您示例中的静态变量foobar_singleton 在每个翻译单元中都是不同的变量(内部链接!)。这是一种表演终结者。

    原题目中的继承只是用来将常用的静态变量“注入”到模板的命名空间中。如果这不是必需的,请不要从 FooBase 派生 Foo,也可以。
    如果出于某种原因需要它,我会私下派生,这应该消除引入额外基类可能遇到的任何副作用。当然,如果 Foo 也继承了其他类,则添加 helper-class 作为最后一个基类。

    如果你想要一个只有标题的解决方案:

    typedef int Bar;
    
    
    template <class DummyType>
    class FooCommonStatics
    {
        static Bar s_bar;
    
        template <class T>
        friend class Foo;
    };
    
    template <class DummyType>
    Bar FooCommonStatics<DummyType>::s_bar;
    
    template <class T>
    class Foo
    {
    public:
        // void is just a dummy-type, any type that's not dependent on T would do
        typedef FooCommonStatics<void> CommonStatics;
    
        Foo()
        {
            CommonStatics::s_bar++;
        }
    
    private:
        T m_something;
    };
    

    【讨论】:

    • 不需要DummyType,你可以使用它应该持有的类型作为参数。
    • 您必须在 FooCommonStatics 中使用模板模板参数才能做到这一点。
    • 不,template&lt;class Data&gt; class Common { static Data s_bar; ...
    • 好吧,我想我理解错了。是的,你可以这样做。但是由于 FooCommonStatics 无论如何都与 Foo 相关联,所以这没有任何意义。好的,如果它们都有不同的类型,可以“重用”FooCommonStatics 类来为 Foo 提供多个静态变量,但是……我会发现这更令人困惑。
    猜你喜欢
    • 2019-06-21
    • 2019-05-10
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多