【问题标题】:Compiler ignores 'const' on function parameter编译器忽略函数参数上的“const”
【发布时间】:2017-07-04 16:19:15
【问题描述】:

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

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*)。

严重性代码描述项目文件行抑制状态 错误 C2664 'void foo(const MyStruct::type)':无法将参数 1 从 'const int *' 转换为 'const MyStruct::type'

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

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

【问题讨论】:

  • const int* ptr 不是 const 指针,它是指向 const 的指针。

标签: c++ visual-studio templates gcc


【解决方案1】:

const int *int * const 之间有一个重要的区别。有关差异的说明,请参阅 this answer

考虑const typename MyStruct&lt;T&gt;::type 的含义。这是MyStruct&lt;T&gt;::type,即const。在这种情况下,它是一个int*,即const。这是一个int* const,一个无法重新分配新地址但仍可用于修改指向的int 的指针。但是,您传入foo&lt;int&gt;(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;
}

【讨论】:

    猜你喜欢
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 2021-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多