【问题标题】:Accessing private/inherited member variables of specialized template访问专用模板的私有/继承成员变量
【发布时间】:2015-01-26 18:34:52
【问题描述】:

我正在尝试使用模板创建一个可以表示不同类型图像的类。为此,我创建了一个通用基类(不应该被初始化),其中模板参数定义了像素值的存储方式(主要是floatunsigned char)。

// Image.h

#pragma once

template<typename T>
class Image
{
public:
    Image () : width (0), height (0), allocatedMemory (0), data (nullptr) {}
    virtual ~Image () { delete [] data; }

protected:
    int width;           // in pixel
    int height;          // in pixel
    int allocatedMemory; // number elements in data
    T* data;             // image data
};

现在,我有另一个类ColorImage,它派生自Image。它添加了另一个定义图像颜色空间的模板参数:

// ColorImage.h

#pragma once

#include "Image.h"

/**
*   Defines various color spaces.
*   Declared outside of class because of template.
**/
enum class ColorSpace 
{ 
    CS_GRAY = 0, CS_RGB, CS_BGR, CS_HSV, CS_LAB, CS_RGBA, CS_BGRA, CS_ARGB
};

template<typename T, ColorSpace C>
class ColorImage;


// Specialise for T = unsigned char

template<ColorSpace C>
class ColorImage<unsigned char, C> : Image<unsigned char>
{
public:
    ColorImage  () : Image () {}
    ~ColorImage () {}

    template<ColorSpace D>
    void convert (ColorImage<unsigned char, D>* output)
    {
        output->width = width;    // error
        output->height = height;  // error
        output->allocatedMemory = allocatedMemory;  // error

        output->foo = 42;  //error

        // ... output->data handling here ...
    }

private:
    int foo;
};

convert() 函数中,我想将一种颜色空间转换为另一种颜色空间。为此,我想将原始图像中的所有数据复制到output-Image。但是,当我调用 output-&gt;width 等时,我收到错误 C2248: 'Image::width' : cannot access private member declaration in class 'Image'

我也无法访问其他专业的其他私人成员。 output-&gt;foo = 42(见上文)抛出无法访问在类“ColorImage”中声明的私有成员。我知道我可以通过将所有完全专业化声明为部分专业化的friend 来解决这个问题,但是,这将导致大量的friend-声明,因为我必须为每一个完全专业化都这样做(对于每个可能的颜色空间)。我也知道我可以只声明像 public setFoo (int value) 这样的东西,但我也不想这样做,因为我不想将变量公开给公众。还有其他方法可以实现吗?

非常感谢。

【问题讨论】:

    标签: c++ templates inheritance template-specialization


    【解决方案1】:

    尝试使用public 派生ColorImage 以获得对其受保护成员的访问权限:

    template<ColorSpace C>
    class ColorImage<unsigned char, C> : public Image<unsigned char> {
        // ...
    };
    

    更多关于 C++ 继承on this SO post.

    【讨论】:

    • 在这种情况下,这不是问题所在。问题是TemplateType&lt;T1&gt;TemplateType&lt;T2&gt; 无关,除了代码中的文本外观。
    猜你喜欢
    • 1970-01-01
    • 2012-10-26
    • 2012-01-04
    • 2016-01-28
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    • 2017-03-16
    • 1970-01-01
    相关资源
    最近更新 更多