D 使用 emplace

问题描述 投票:0回答:1

我正在尝试在这段代码中使用 emplace :

class motionFactory{
        public:
            this(double velocity, double gravity, double angle){
                this.velocity = velocity;
                this.gravity = gravity;
                this.angle = angle;
            }
            motion getMotion(double step) const{
                auto ptr = malloc(motion.sizeof);
                return emplace!motion(ptr, velocity, gravity, angle, step);
            }
        private:
            double velocity;
            double gravity;
            double angle;
    }

    class motion : motionFactory{
        public:
            this(double velocity, double gravity, double angle, double step){
                super(velocity, gravity, angle);
                this.current = 0;
                this.step = step;
                this.range = getCurrentRange();
            }
        private:
            double current;
            const double step;
            const double range;

    }

我不断收到这个奇怪的编译错误。

error: template std.conv.emplace cannot deduce function from argument types !(motion)(motion, const(double), const(double), const(double), double), candidates are:
  102 |                 return emplace!motion(ptr, velocity, gravity, angle, step);

看了文档太久却无济于事,我很茫然。 请帮忙

d
1个回答
0
投票

emplace
第一个参数不是一个 untyped 指针,而是一个作为要放置的对象类型的指针。

这是一个问题。第二个问题是

motion.sizeof
将是 类引用 的大小,换句话说,是指针的大小。您想要类数据的大小。为了得到这个,你需要使用
__traits(classInstanceSize, motion)

getMotion
函数应更改为:

            motion getMotion(double step) const{
                auto ptr = cast(motion)malloc(__traits(classInstanceSize, motion));
                return emplace(ptr, velocity, gravity, angle, step);
            }
© www.soinside.com 2019 - 2024. All rights reserved.