提问人:nvn 提问时间:8/4/2023 最后编辑:nvn 更新时间:8/4/2023 访问量:86
删除 const 时模板中的编译错误
Compilation error in template when const is removed
问:
template<typename T>
void func(const T &x) {
cout << "base template "<<x<<"\n";
}
template<>
void func(const int &x) {
cout << "int specialization "<<x<<"\n";
}
template<>
void func(const double &x) {
cout << "double specialization "<<x<<"\n";
}
int main() {
int five = 5;
func(five); // prints int specialization 5
double d = 3.14;
func<int>(d); // prints int specialization 3
}
现在删除了const
template<typename T>
void func( T &x) {
cout << "base template "<<x<<"\n";
}
template<>
void func( int &x) {
cout << "int specialization "<<x<<"\n";
}
template<>
void func( double &x) {
cout << "double specialization "<<x<<"\n";
}
int main() {
int five = 5;
func(five); // prints int specialization 5
double d = 3.14;
func<int>(d); // throws compile error
}
为什么我在版本中一切都编译良好?func<int>(d)
const
错误 C2664“void func(int &)”:无法将参数 1 从“double”转换为“int &”
当我自己尝试一些模板专用化示例时,我遇到了这个问题。
我正在寻找可能有帮助的阅读链接和帖子。
答:
10赞
wohlstad
8/4/2023
#1
该问题实际上与模板无关:
您需要转换为 an 才能成为需要引用的函数的参数。double d
int
int
但是,由于转换后是临时的(即 R 值),因此它不能绑定到 ,而只能绑定到 .int
int &
const int &
您可以在没有任何模板的情况下观察到这一点:
void func1(const int& x)
{
}
void func2(int& x)
{
}
int main()
{
double d = 3.14;
func1(d); // This compiles.
func2(d); // This does not. Error on MSVC: cannot convert argument 1 from 'double' to 'int &'
}
评论
const
x
d
int
double
const
double d
int
void func(int&)
func(d);
template <typename T> struct temp { T var; temp(T value) : var{value} {} operator T&() { return var; } };
func<int>(temp<int>(d));