gpt4 book ai didi

c++ - 编译器忽略函数参数上的 'const'

转载 作者:太空狗 更新时间:2023-10-29 20:10:05 26 4
gpt4 key购买 nike

我有一个编译器错误的问题,看看这段代码:

template<class T>
struct MyStruct
{
};

template<>
struct MyStruct<int>
{
typedef int* type;
};

template<class T>
void foo(const typename MyStruct<T>::type myType)
{
}

int main()
{
const int* ptr = NULL;
foo<int>(ptr);

return 0;
}

问题是编译器忽略了 foo 函数上的“const”,使得对 foo 的调用是非法的(const int* 到 int*)。

Severity Code Description Project File Line Suppression State Error C2664 'void foo(const MyStruct::type)': cannot convert argument 1 from 'const int *' to 'const MyStruct::type'

我已经在 Visual Studio 和 gcc 的 5.3 编译器中测试了以下代码,它们都出现了同样的错误。

编译器是故意这样做的吗?为什么会这样?

最佳答案

const int * 之间有一个重要的区别和 int * const .参见 this answer以获得对差异的解释。

考虑一下const typename MyStruct<T>::type方法。这是一个MyStruct<T>::type那是 const .在这种情况下,它是一个 int*那是 const .这是 int* const , 一个不能重新分配新地址但仍可用于修改指向的 int 的指针.但是,您传入的指针 foo<int>(ptr)const int *无法转换为 int * const ,因为它会丢弃 const限定词。

实现你想要的,const在使它成为指针之前必须是类型的一部分。它不能在事后添加,否则将始终被解释为 T * const .您可以使用类型特征来删除类型的指针部分,添加 const,然后使其成为指针。

#include <type_traits>

template<class T>
struct MyStruct { };

template<>
struct MyStruct<int> {
typedef int* type;
};

template<class T>
void foo( std::add_const_t<std::remove_pointer_t<typename MyStruct<T>::type>> * myType) {}

int main()
{
const int* ptr = nullptr;
foo<int>(ptr);

return 0;
}

关于c++ - 编译器忽略函数参数上的 'const',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42258970/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com