c++ - 错误 : invalid conversion from "const ..." to "..." error message when using templates

标签 c++ templates

所以我想弄清楚 C++ 模板是如何工作的,但我运气不太好。我创建了以下模板:

template<class TValue>
class Value {
public:
    virtual ~Value();

    inline TValue value() const { return _value; }

    virtual int serialize(unsigned char* buffer, int bufferSize) const = 0;

protected:
    Value(TValue value, const ValueType& valueType) : _value(value), _valueType(&valueType) {}

private:
    TValue _value;
    ValueType* _valueType;
};

template<class TValue>
class NumericValue : public Value<TValue> {
protected:
    NumericValue(TValue value, const ValueType& valueType) : Value<TValue>(value, valueType) {}
};

然后我创建了一个类:

class U16Value : public NumericValue<u16> {
public:
    U16Value(u16 value) : NumericValue<u16>(value, ValueType::U16) {}
}

不幸的是,这不会编译。我在这一行收到一个错误:

Value(TValue value, const ValueType& valueType) : _value(value), _valueType(&valueType) {}

也就是说:

error: invalid conversion from const tnp::ValueType* to tnp::ValueType* [-fpermissive]

有人能告诉我为什么会这样吗?

谢谢。

最佳答案

成员 _valueType 声明为指向非 const 对象 (ValueType*) 的指针,并且您尝试使用 (&valueType) 初始化的指针是指向 const 对象 (const ValueType*) 的指针,因为您引用的是 const 引用。

关于c++ - 错误 : invalid conversion from "const ..." to "..." error message when using templates,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17972509/

相关文章:

c++ - 外部模板 : declaration does not declare anything

c++ - 当 cv::minMaxLoc 返回点 (-1, -1) 作为最小和最大位置时,这意味着什么?

c++ - 为什么这段代码执行两次相同的操作?

python - 从字符串中随机选择

c++ - 如何使用 Google Mock 模拟模板化方法?

javascript - 在循环中的仪表板 ui_template (node-red) 中创建复选框并将检查状态分配给输出 msg.payload

c++ - 模板类与模板成员类

c++ - Visual Studio 中带有 Autos 变量的锁定图标。它表示什么?

c# - 寻找教程或基本信息来帮助我开始在 C# 中为初学者实现 C/C++ API

c++ - 用户定义类型的优先级队列