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

标签 c++ visual-studio templates gcc

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

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/

相关文章:

c++ - 从另一个类中访问对象的类方法,C++

java - 如何将 WaitForMultipleObjects 移植到 Java?

c++ - 我如何从 HBITMAP 获取字节数组

php - 非常简单的 PHP 模板...没有 `eval` 可以工作吗?

具有函数声明/原型(prototype)和定义的 C++ 模板

c++ - 将 std::bind 创建的对象传递给函数的正确方法是什么?

c++ - 为什么 std::function 在 C++11 中不隐式转换为 bool?

visual-studio - 为什么我的 MSBuild 文件中需要一个单独的项目?

asp.net - Visual Studio 不显示 'Manage Bower Packages...' 上下文菜单

c++ - 将 std::get 与枚举类一起使用时需要 static_cast