Kon*_*nvt 2 c++ templates std template-meta-programming c++17
我正在尝试模拟std::any
,我的想法是使用基类指针指向不同类型的模板派生类,来实现存储不同类型数据的功能,比如std::any
;因此我写了以下代码:
class Any {
TypeBase *_ptr;
public:
Any(): _ptr(nullptr) {}
Any(const Any &other): Any() { _ptr = other._ptr->copy(); }
Any(Any&& _other): Any() {
_ptr = _other._ptr;
_other._ptr = nullptr;
}
template<typename T> Any(T&& _data): Any() {
/*
* this function attempts to capture rvalue param
*/
_ptr = new Container<T>(std::forward<T>(_data));
}
~Any() { delete _ptr; }
template<typename T> T& data_cast() const {
if (_ptr == nullptr)
throw std::runtime_error("Container empty");
return static_cast<Container<T>*>(_ptr)->data;
}
};
Run Code Online (Sandbox Code Playgroud)
这些工具包类是:
struct TypeBase {
virtual ~TypeBase() {}
virtual TypeBase* copy() = 0;
};
template<typename T> struct Container: public TypeBase {
T data; // those datas will store here
Container() = delete;
template<typename U> Container(U&& _data): data(std::forward<U>(_data)) {}
virtual ~Container() {}
virtual TypeBase* copy() override { return (new Container<T>(data)); }
};
Run Code Online (Sandbox Code Playgroud)
我的问题是,当我使用这样的代码时,生成的数据不会存储在Container
:
#include <stdexcept>
// paste the definition given above
int main()
{
double y = 13.32;
Any a = y;
std::cout << "The data of 'a' is: " << a.data_cast<double>() << std::endl;
/* it doesn't work here, only outputs some wrong number */
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是我的理解:编译器使用 隐式为我构造一个“Any”对象y
,然后调用复制构造函数来初始化a
.
我期望的是“Any”会接受左值和右值数据以减少复制开销,但显然我编写它的方式存在一些我没有意识到的问题。
我尝试使用调试器跟踪进程,发现函数调用过程完全符合我的预期。尽管我可以看到指针 ina
是有效的,但输出仍然很奇怪:The data of a is: 3.10818e-317
。
我很难找到问题的根源,所以我希望有人指导我,或者也许我只是写了错误的代码,有人可以指出它。
您正在构造一个Container<double&>
,但稍后将指向它的指针转换为Container<double>*
.
当您将左值传递给转发引用时,模板参数将被推导为引用类型。也就是说,在
template<typename T> Any(T&& _data): Any() {
_ptr = new Container<T>(std::forward<T>(_data));
}
Run Code Online (Sandbox Code Playgroud)
当您传递左值时y
,T
将被推导为double&
。这样,_data
is的类型double& &&
就会折叠为double&
. 如果T
是double
那么_data
将是 a double&&
,它无法绑定到左值。
解决方案非常简单:只需应用std::remove_reference_t
:
template <typename T>
Any(T&& data) : Any() {
using DataT = std::remove_reference_t<T>;
_ptr = new Container<DataT>(std::forward<T>(data));
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
65 次 |
最近记录: |