class NDArray{
private:
Context ctx_;
typeFlag dtype_;
std::vector<size_t> shape_;
std::shared_ptr<TBlob<dtype_, ctx_.dev_type_, ctx_.dev_id_> > data_;
public:
// constructor
NDArray();
NDArray(const NDArray &obj);
explicit NDArray(const size_t size);
我想在构造函数之后实例化data_
成员,在此初始化ctx_
和dtype_
成员
inline NDArray::NDArray(): ctx_(Context()), shape_{0}, dtype_(typeFlag::kFloat32), {}
inline NDArray::NDArray(const NDArray &obj): ctx_(obj.ctx_), shape_(obj.shape_), dtype_(obj.dtype_), data_(obj.data_){}
然后我得到了错误:
NDArray.hpp:18:31: error: invalid use of non-static data member ‘mxnet::NDArray::dtype_’
std::shared_ptr<TBlob<dtype_, ctx_.dev_type_, ctx_.dev_id_> data_;
^
NDArray.hpp:16:18: note: declared here
typeFlag dtype_;
我该怎么做才能实现自己的目标?你能帮我吗
编辑
template<typeFlag dtype, Context::DeviceType ctx_type, int ctx_id>
class TBlob{
friend class NDArray;
public:
TBlob();
TBlob(const TBlob<dtype, ctx_type, ctx_id> &obj);
explicit TBlob(const size_t &size);
explicit TBlob(const std::vector<size_t> &shape);
TBlob(const float *data, const size_t size);
TBlob(const float *data, const std::vector<size_t> shape);
TBlob(const uint8_t *data, const size_t size);
TBlob(const uint8_t *data, const std::vector<size_t> shape);
~TBlob();
private:
void *dptr_;
std::vector<size_t> shape_;
};
template<typeFlag dtype, Context::DeviceType ctx_type, int ctx_id>
inline TBlob<dtype, ctx_type, ctx_id>::TBlob(): dptr_(nullptr), shape_{0} {}
template<typeFlag dtype, Context::DeviceType ctx_type, int ctx_id>
inline TBlob<dtype, ctx_type, ctx_id>::TBlob(const TBlob<dtype, ctx_type, ctx_id> &obj): dptr_(obj.dptr_), shape_(obj.shape_) {}
答案 0 :(得分:1)
这是我能想到的最接近您想要的东西,但我不知道它是否对您有用。请注意,由于使用虚方法,因此会产生少量开销。我使用了一个更简单的示例,但它或多或少是等效的。
#include <memory>
#include <utility>
#include <iostream>
// Base interface class for the templated type
class TemplInterface
{
public:
// Templated class (pure?) virtual method declarations
// (parameter and return types cannot depend on template values)
virtual void print_value() const = 0;
};
// Actual templated type
template<int i>
class Templ : public TemplInterface
{
public:
// Templated class implementation
virtual void print_value() const
{
std::cout << "Value: " << i << std::endl;
}
};
// Class containing the templated type
class Outer
{
private:
// Member pointer to non-template base type
std::shared_ptr<TemplInterface> _templ;
// Class constructor is private
Outer(std::shared_ptr<TemplInterface> templ) : _templ(std::move(templ)) {}
public:
// Factory function
template<int i>
static Outer make()
{
return Outer(std::make_shared<Templ<i>>());
}
void print_templ() const
{
_templ->print_value();
}
};
int main()
{
Outer a = Outer::make<3>();
a.print_templ();
return 0;
}
输出:
Value: 3