【问题标题】:pointer to incomplete class type is not allowed in a partial template class部分模板类中不允许指向不完整类类型的指针
【发布时间】:2017-01-24 09:14:05
【问题描述】:

我正在修改项目中的一些现有代码。我有一个模板类 Param 和一个用于头文件中参数的部分专用模板类,如下所示:

template<class ValueType>
struct Param
{
    static void add(ParameterCode code, ValueType value, ParameterAttributes attributes)
    {
    }

    static PreSetResultType preSetActions(ParameterCode code, ValueType& value)
    {
        return (SUCCESS);
    }

    static void set(ParameterCode code, ValueType value)
    {
    }

    static ValueType get(ParameterCode code)
    {
        ValueType value = ValueType();
        return (value);
    }

    static void serialize(ParameterCode code, vector<uint8_t>& byteArray)
    {
    }

    static ValueType deserialize(const vector<uint8_t>& byteArray)
    {
        return (*reinterpret_cast<const ValueType*>(byteArray.begin()));
    }
};

/* template function specialization for pointer types */
template<class ValueType>
struct Param<ValueType*>
{
    static void add(ParameterCode code, ValueType* value, ParameterAttributes attributes)
    {
    }

    static PreSetResultType preSetActions(ParameterCode code, ValueType*& config)
    {
        return (SUCCESS);
    }

    static void set(ParameterCode code, ValueType* pObjNew)
    {
        pObjNew->serialize(serializedObject); //error line 54
    }

    static ValueType* get(ParameterCode code)
    {
        void* value = NULL;
        return ((ValueType*)value);
    }

    static void serialize(ParameterCode code, vector<uint8_t>& byteArray)
    {
        ValueType* obj = get(code);
        obj->serialize(byteArray); //error line 60
    }

    static ValueType* deserialize(const vector<uint8_t>& byteArray)
    {
        return (ValueType::deserialize(byteArray)); //error line 65
    }
};

在模板类的专业化中,我收到以下错误消息: 第 65 行的“不允许使用不完整类型的 Parameters.h” “不允许指向不完整类类型的指针 Parameters.h”在第 54 行和第 60 行

我知道模板类的特化类型不完整,但编译器应该在编译时解决它,或者我需要某种前向声明。这两个类都在同一个 .h 文件中。 这里只复制相关代码。 感谢您的帮助。

【问题讨论】:

  • 哪一行是 54,60 和 65?你修改了什么?以前用过吗?
  • 代码之前可以运行,我只是删除了一些我的项目不需要的头文件。现在代码中已经提到了这些行。
  • 在它工作之前,你删除了一些包含,现在它不工作了。为什么您仍然认为不需要这些包含?
  • 因为这部分代码是不需要的,这并不能解释为什么编译器会在这些代码行出现错误。
  • 通过添加缺失的部分,我无法重现问题Demo。提供 MCVE。

标签: c++ templates template-specialization


【解决方案1】:

您可能忘记在某处包含一个带有参数类定义的头文件。这是最常见的错误原因。

当您不使用已声明类中的字段时,前向声明有效。开始使用字段后,您需要定义此类。

【讨论】:

  • 问题是在其他地方,我用一个由于头文件删除而不可用的类实例化了这个模板的一个对象。所以,我也删除了那部分代码。问题是编译器没有在那里抱怨:)
猜你喜欢
  • 2021-12-31
  • 2012-08-15
  • 2015-10-09
  • 1970-01-01
  • 2017-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多