删除 const 时模板中的编译错误

Compilation error in template when const is removed

提问人:nvn 提问时间:8/4/2023 最后编辑:nvn 更新时间:8/4/2023 访问量:86

问:

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 &”

当我自己尝试一些模板专用化示例时,我遇到了这个问题。

我正在寻找可能有帮助的阅读链接和帖子。

C++ 参数传递 隐式转换

评论

4赞 wohlstad 8/4/2023
删除允许修改 ,这是一个问题,因为您作为参数传递的实际上不是(而是 )。使用 allows 绑定到临时的,这是将 yout 转换为 .constxdintdoubleconstdouble dint
4赞 Pete Becker 8/4/2023
一大早,我还没有检查,但我怀疑模板在这里分散了注意力。尝试使用单个函数,并使用 调用它。void func(int&)func(d);
0赞 463035818_is_not_an_ai 8/4/2023
请在问题中包括编译器错误。我持有有价值的信息
0赞 Eljay 8/4/2023
您可以提供一个显式的临时解决方案来解决语言约束问题。 然后通过 调用函数。不要在实际代码中这样做;此处显示用于教育目的。template <typename T> struct temp { T var; temp(T value) : var{value} {} operator T&() { return var; } };func<int>(temp<int>(d));

答:

10赞 wohlstad 8/4/2023 #1

该问题实际上与模板无关:

您需要转换为 an 才能成为需要引用的函数的参数。double dintint

但是,由于转换后是临时的(即 R 值),因此它不能绑定到 ,而只能绑定到 .intint &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 &'
}