使用常量限定符将参数传递到模板函数时出错
Error passing arguments to template function with const qualifier
我有这个代码示例:
#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
,编译器需要推导T
和U
,其中T
是模板模板参数。需要的是:
-
T
std::auto_ptr
,U
在第一次调用中int
-
T
const std::auto_ptr
,U
在第二次调用中int
还有你的问题:T
本身不能const std::auto_ptr
,因为它将类型属性const
与模板std::auto_ptr
组合在一起,而模板这不是一个有效的类型。
相关文章:
- 类中私有结构的构造函数出错
- 字符串验证函数出错
- 我的类默认构造函数出错
- Dev-C++和Code::Blocks中的析构函数出错
- int对的哈希函数出错
- MSVC 编译器错误导致迭代器和友元函数出错
- 复制构造函数出错
- 使用 WinSock2 开发,使用 CreateThread() 函数出错
- 链接列表的Push_back函数出错
- 结构初始化中的隐式复制构造函数出错
- 异步函数出错
- 编译器错误消息错误:令牌之前的预期')' '*'。我的构造函数出错
- c++中使用std::bind和std::函数出错
- 在vector排序中使用c++模板函数出错
- 使用std::for_each lambda函数出错
- 二叉搜索树插入函数出错
- 调用类的函数出错
- c++使用删除函数出错
- 使用已删除的函数出错
- 调用构造函数出错