带 const 和不带 const 限定符的 typedef [英] typedef with const and without const qualifier

查看:31
本文介绍了带 const 和不带 const 限定符的 typedef的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    typedef void* TVPtr;
    typedef const void* CTVPtr;

const TVPtr func3 (const TVPtr p)
{
    return p;
}

const void* func4 (const void* p)
{
    return p;
}

CTVPtr func5 (CTVPtr p)
{
    return p;
}


int main ()
{
    const uint64_t i = 10;

    func3(&i);  // compilation error here
                // cannot convert argument 1 from 'const uint64_t *' 
                // to 'const TVPtr' Conversion loses qualifiers    
    func4(&i);  // no compilation error
    func5(&i);  // no compilation error
    return 0;

}

我不明白为什么在一种情况下有错误,而在另外两种情况下没有?

I do not understand why there is error is one case and not in the other two?

推荐答案

const TVPtr

意思是:

void * const  //correct

不是这个:

const void*   //wrong

你似乎认为.

这就是为什么我认为将 const 放在类型之后是一种更好的做法的原因之一.所以如果你有这种做法:

This is one reason why I believe putting const after the type is a better practice. So if you have this practice:

void const * x;

代替

const void * x; //same as void const *x!

然后它有助于 typedef 和模板.

then it helps with typedef and template.

以这个 typedef 为例:

For example, take this typedef:

typedef void* voidptr;

现在,如果您编写以下内容并尝试想象它是什么:

Now if you write the following and try to visualize what it is:

voidptr const x;

那么你更有可能把它想象成:

then you're more likely to visualize it as:

void* const x; //correct

事实就是这样.

在类型之前使用 const 是违反直觉的:

With const before the type is counter-intuitive:

const voidptr x;

似乎是:

const void* x; //wrong

实际上是错误的——仍然是这样:

which is actually wrong — it is still this:

 void* const x; //correct

因此将 const 放在类型之后有助于可视化最终类型.

So putting const after the type helps visualizing the final type.

这篇关于带 const 和不带 const 限定符的 typedef的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆