将模板化 T 定义为指针

Define a templated T as pointer

本文关键字:定义 指针      更新时间:2023-10-16

我想使用以下代码定义一些通用指针(?但不是空指针):

class A
{
template<typename T>
using ptr = T*;
using ubyte = uint8_t;
public:
    const ptr<ubyte>
    getColor1() const {
        return &colors[0];
    }
    const ubyte*
    getColor2() const {
        return &colors[0];
    }

private:
    ubyte colors[4];
};

但是,getColor1()不会编译。这两个函数有什么区别?

海湾合作委员会 说:

error: invalid conversion from 'const ubyte* {aka const unsigned char*}' to 'A::ptr<unsigned char> {aka unsigned char*}' [-fpermissive]|

更新:

删除的答案说我可以这样做:

//option 1
template<typename T>
using const_ptr = const T*;

//option 2
const ptr<ubyte>
getColor()  //remove cv-qualifier
{
    return &colors[0];
}

从选项 1,

它现在构造为const constconst const是什么意思?

从选项 2,

为什么只删除 cv 限定符就可以编译?

const ptr<ubyte>const (ubyte *)相同,这与const ubyte (*)不同。您正在尝试返回指向非常量charconst指针,编译器不允许这样做,因为您已将函数本身声明为const ;因此,所有成员都成为const。编译器不会在没有const_cast的情况下自动将 const 转换为非 const 。

为了使区别更清楚,第一个是指向非常量char的常量指针,第二个是指向常量char的非常量指针。第一个允许指向的字符更改,即使指针本身无法更改。由于该函数被标记为const因此它无法返回任何允许修改其成员的内容。

修复它的最佳方法:

ptr<const ubyte>
getColor1() const {
    return &colors[0];
}

由于ptr模板的语法,const ptr<ubyte>首先使其成为ubyte*,然后应用常量,从而产生一个ubyte * const,一个指向 ubyte 的常量指针。

为了返回指向 const ubyte 的指针,您需要将const ubyte馈送到指针模板中,因此首先应用常量:

ptr<const ubyte>

1)"const const 是什么意思?

const T* const pT = new T;

表示常量指针 pT - 您不能将 pT 分配给另一个对象;到 T 类型的 const 对象 - 您无法更改 pT 指向的对象。

2)"为什么只是删除cv限定符就可以编译这个?

getColor1()

没有 const 修饰符的方法可以修改对象。它现在返回 A::ubyte*,可以转换为 const 类型,例如声明为返回类型:A::ubyte* const (const ptr