2

我有这个代码示例:

#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' 接受通用参数,而不管限定符如何,但是在第二种情况下,函数 'func2' 在参数具有 const 限定符时失败。为什么会这样?

这是编译错误:

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
4

1 回答 1

1

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

  • Tstd::auto_ptr<int>第一次通话中
  • Tconst std::auto_ptr<int>第二次通话中

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

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

  • Tstd::auto_ptr,Uint在第一次通话中
  • Tconst std::auto_ptrUint第二次通话中

还有你的问题:T不能是const std::auto_ptr它自己,因为它结合了一个类型属性和一个不是有效类型const的模板。std::auto_ptr

于 2013-09-27T15:27:23.460 回答