【发布时间】:2015-08-22 05:05:27
【问题描述】:
来自 Matthew H. Austern 的 STL 书籍,固定大小数组的“块”类。
template<class T, size_t N>
struct Block
{
// Various typedef's
// Implementations of begin() and end().
reference operator[](size_t nIndex)
{
return data[nIndex];
}
// I added this overloaded operator+
T* operator+(const size_t nIncrement)
{
return (data + nIncrement);
}
// I added this overloaded cast operator
// **Why is this cast operator not being called?**
operator T*()
{
return data;
}
T data[N];
};
这就是我想要做的:
Block<int, 10> tArray; // Populate tArray.
// I want to use std::sort() in the same way as I would
// for a regular array.
sort(tArray, tArray + tArray.size());
我得到编译器错误:
错误:没有匹配的函数调用 sort(Block&, int*)
为什么编译器不知道重载的强制转换运算符?
以下全部编译:
sort(tArray + 0, tArray + tArray.size());
sort(static_cast<int*>(tArray), tArray + tArray.size());
sort(tArray.begin(), tArray.end());
显然,强制转换运算符的重载是有问题的 我不知道的工作。有什么想法吗?
谢谢。
约束:
我可能不会使用 C++11(所以没有来自 C++11 的 std::array)。 我可能不会使用 begin() 或 end()。
【问题讨论】:
-
在决定模板参数时不考虑转换运算符。如果 sort 不是模板函数,您的代码将起作用。 Cast 运算符通常不是一个好主意,
-
FWIW,有一个
boost::array就像现在的标准一样工作。 -
正如上面约翰所说。由于 std::sort 是一个模板函数,它试图从参数中决定模板的类型,并且不知道选择哪个。 sort
(tArray, tArray+tArray.size()) 应该可以工作 -
我认为我能做的最好的事情是:sort
(arr, arr+ size);