为什么我必须将这些引用参数声明为 const 或按值传递?
Why do I have to declare these reference paramaters const or pass by value?
#include <vector>
#include <iostream>
using namespace std;
static const int NOT_FOUND = -1;
template <class sequence, class T>
int binarySearch(sequence& seq, int low, int high, T& item)
{
//..
}
template <class sequence, class T>
int binarySearch(const sequence& seq, const T& item)
{
if (seq.size() == 0)
return NOT_FOUND;
return binarySearch(seq, 0, seq.size() - 1, item);
}
int main()
{
vector<int> t1 = {0, 3 ,45, 94};
cout << binarySearch(t1, 0);
//binarySearch(t1, 0, t1.size() - 1, 45);
return 0;
}
为什么编译器不接受:
template <class sequence, class T>
int binarySearch(sequence& seq, T& item)
?
此外,为什么程序按规定编译,但调用
binarySearch(t1, 0, t1.size() - 1, 45);
from main 编译不了?
任何情况下的编译器错误都是“没有匹配函数来调用 'binarySearch'。
问题是您不能将临时对象绑定到非常量引用。
binarySearch(t1, 0);
^---- this is a temporary
如果您将 0
存储在一个变量中并使用它,则 non-const version would work.
§ 8.5.4
— Otherwise, if T is a reference type, a prvalue temporary of the type referenced by T is copy-list-initialized or direct-list-initialized, depending on the kind of initialization for the reference, and the reference is bound to that temporary. [ Note: As usual, the binding will fail and the program is ill-formed if the reference type is an lvalue reference to a non-const type. —end note
#include <vector>
#include <iostream>
using namespace std;
static const int NOT_FOUND = -1;
template <class sequence, class T>
int binarySearch(sequence& seq, int low, int high, T& item)
{
//..
}
template <class sequence, class T>
int binarySearch(const sequence& seq, const T& item)
{
if (seq.size() == 0)
return NOT_FOUND;
return binarySearch(seq, 0, seq.size() - 1, item);
}
int main()
{
vector<int> t1 = {0, 3 ,45, 94};
cout << binarySearch(t1, 0);
//binarySearch(t1, 0, t1.size() - 1, 45);
return 0;
}
为什么编译器不接受:
template <class sequence, class T>
int binarySearch(sequence& seq, T& item)
?
此外,为什么程序按规定编译,但调用
binarySearch(t1, 0, t1.size() - 1, 45);
from main 编译不了?
任何情况下的编译器错误都是“没有匹配函数来调用 'binarySearch'。
问题是您不能将临时对象绑定到非常量引用。
binarySearch(t1, 0);
^---- this is a temporary
如果您将 0
存储在一个变量中并使用它,则 non-const version would work.
§ 8.5.4
— Otherwise, if T is a reference type, a prvalue temporary of the type referenced by T is copy-list-initialized or direct-list-initialized, depending on the kind of initialization for the reference, and the reference is bound to that temporary. [ Note: As usual, the binding will fail and the program is ill-formed if the reference type is an lvalue reference to a non-const type. —end note