模板类中私有weak_ptr的定义
Definition of private weak_ptr in template class
首先:我是C++新手,所以不要评判我。:)
我尝试在模板类中定义静态weak_ptr,以便在所有实例上使用它。
这是我的代码:
template <class T> class my_template : public my_class {
protected:
std::shared_ptr<T> sp;
virtual bool init_impl() {
sp = wp.lock();
...
return true;
}
private:
static std::weak_ptr<T> wp;
};
但是编译给了我一个错误:
.../my_template.hpp:7: undefined reference to 'my_template<my_class2>::wp'
谁能帮忙?我只是不明白。
只需添加相同的标头:
template<class T>
std::weak_ptr<T> my_template<T>::wp;
对我有用! :)
根据您的注释,您没有单独的.cpp文件可用于定义static
变量的存储。 在这种情况下,您可以公开一个 static
方法,该方法在内部声明自己的static
变量:
template <class T> class my_template : public my_class {
protected:
std::shared_ptr<T> sp;
virtual bool init_impl() {
sp = get_wp().lock();
...
return true;
}
private:
static std::weak_ptr<T>& get_wp()
{
static std::weak_ptr<T> wp;
return wp;
}
};
当变量在函数内部声明static
时,当函数退出时,它不会超出范围,它会被保留以供后续函数调用使用。
相关文章:
- 在提升multi_index容器中,是否定义了"default index"?
- #定义c-预处理器常量..我做错了什么
- 用C++中的一个变量定义一个常量
- 部分定义/别名模板模板参数
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- #为""定义宏;静态";针对不同的上下文
- 如何确保C++函数在定义之前声明(如override关键字)
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 在命名空间中定义函数还是限定函数
- 此代码是否违反一个定义规则
- 编译C++时未定义的引用
- 不同翻译单元中不可重载的非内联函数定义
- 为什么在定义函数之前先声明它
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 在类定义之后定义一个私有方法
- OpenCV - Ptr 语法和类定义/声明 - 混淆?
- ++*ptr++ 在 c++ 中是未定义的行为吗?
- 为什么 gcc 4.9.0 中没有定义"void operator delete(void* ptr, std::size_t size) noexcept;"?
- 是指向无效内存时sizeof(*ptr)未定义的行为