删除 const 时模板中出现编译错误

nvn*_*nvn 3 c++ parameter-passing implicit-conversion

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
}

Run Code Online (Sandbox Code Playgroud)

现在已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
}
Run Code Online (Sandbox Code Playgroud)

为什么我在一切都编译正常func<int>(d)的const版本中出现编译错误?

错误 C2664 'void func(int &)':无法将参数 1 从 'double' 转换为 'int &'

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

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

woh*_*tad 10

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

您double d需要转换为 anint才能成为需要 a 的函数的参数int。

但由于转换后的值int是临时的(即 R 值),因此它不能绑定到 an int &,而只能绑定到 aconst 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 &'
}
Run Code Online (Sandbox Code Playgroud)