【问题标题】:C++ Templates - How to use across multiple MTU'sC++ 模板 - 如何跨多个 MTU 使用
【发布时间】:2011-03-12 00:51:08
【问题描述】:
class A : boost::noncopyable {
    int type;

    A(int type, enum e) : type(type) { /* ... */ }
}
typedef boost::shared_ptr<A> A_ptr;


template <enum VAR>
class B : boost::noncopyable {
    static A_ptr x, y;

    B() {
        if (!x.get()) {
            x.reset(new A(0, VAR));
        }
        if (!y.get()) {
            y.reset(new A(1, VAR));
        }
    }
}

我想根据模板有几种类型的“B”;这样,它将保持单独的静态和“跟踪”它们自己的xy (A_ptrs)。

问题:

a) 如何在模板正常工作的情况下将其设置为标头/源配置?

b) 我应该形成一个“createA”函数而不是x.reset(new A(0, VAR));

c) 未初始化时,shared_ptr.get() 是否保证返回 0(即布尔表达式中的 false)?

我应该将 b) 和 c) 拆分为多个 SO 问题吗?

【问题讨论】:

  • 注: shared_ptr 不能“未初始化”,如果您不提供初始化程序,它将被默认构造。

标签: c++ design-patterns templates boost shared-ptr


【解决方案1】:

a) 像这样设置它:

啊哈:

#ifndef A_HEADER_GUARD
#define A_HEADER_GUARD

class A {...};

#endif

A.cpp:

// A::method1 implementation
// A::method2 implementation
// etc...

B.h:

#ifndef B_HEADER_GUARD
#define B_HEADER_GUARD

#include "A.h"

template <enum VAR> class B {...}

#endif

请注意,B 类不能在 cpp 文件中实现。这是因为 B 类是一个模板,它的实现必须对任何实例化模板的人完全可见。

确保您了解header guards 的用法(又名包括警卫)。


b) 编写私有辅助方法来“分解”经常重复的代码是很正常的,我会说甚至鼓励。


c) 是的,shared_ptr::get() 在未初始化时保证为 0,如 documentation 中的 后置条件 子句所述。

您可以只检查shared_ptr 本身,而不是在条件表达式中检查shared_ptr::get()。在布尔上下文中使用时,它会自动将自身转换为bool。例如:

shared_ptr<A> a_ptr;
if (!a_ptr)
    cout << "a_ptr not initialized!";

这是检查智能指针有效性的惯用方式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-31
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    • 2021-11-12
    • 2015-05-12
    • 1970-01-01
    相关资源
    最近更新 更多