使用常量限定符将参数传递到模板函数时出错

Error passing arguments to template function with const qualifier

本文关键字:函数 出错 参数传递 常量      更新时间:2023-10-16

我有这个代码示例:

#include <iostream>
#include <memory>
template <typename T>
void func1(T& value)
{
    std::cout << "passed 1 ..." << std::endl;
}
template <template <typename> class T, typename U>
void func2(T<U>& value)
{
    std::cout << "passed 2 ..." << std::endl;
}
int main()
{
    std::auto_ptr<int> a;
    const std::auto_ptr<int> ca;
    // case 1: using func1
    func1(a);  // OK
    func1(ca); // OK
    // case 2: using func2
    func2(a);  // OK
    func2(ca); // Compilation error
    return 0;
}

在第一种情况下,函数 'func1' 接受泛型参数,而不考虑限定符,但是第二种情况,当参数具有 const 限定符时,函数 'func2' 失败。为什么会这样?

这是编译错误:

make all 
Building file: ../src/Test2.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/Test2.d" -MT"src/Test2.d" -o "src/Test2.o" "../src/Test2.cpp"
../src/Test2.cpp: In function ‘int main()’:
../src/Test2.cpp:27: error: invalid initialization of reference of type ‘std::auto_ptr<int>&’ from expression of type ‘const std::auto_ptr<int>’
../src/Test2.cpp:11: error: in passing argument 1 of ‘void func2(T<U>&) [with T = std::auto_ptr, U = int]’
make: *** [src/Test2.o] Error 1
问题是在

func1 的情况下,编译器需要推导T,我们得到

  • T在第一次调用中std::auto_ptr<int>
  • T在第二次调用中const std::auto_ptr<int>

在这两种情况下T本身都是有效的。

现在对于func2,编译器需要推导TU,其中T是模板模板参数。需要的是:

  • T std::auto_ptrU在第一次调用中int
  • T const std::auto_ptrU在第二次调用中int

还有你的问题:T本身不能const std::auto_ptr,因为它将类型属性const与模板std::auto_ptr组合在一起,而模板这不是一个有效的类型。