Reputation: 21
From Matthew H. Austern's STL book, "Block" class for a fixed size array.
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];
};
This is what I am trying to do:
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());
I get the compiler error:
error: no matching function for call to sort(Block&, int*)
Why isn't the compiler aware of the overloaded cast operator?
All of the following compile:
sort(tArray + 0, tArray + tArray.size());
sort(static_cast<int*>(tArray), tArray + tArray.size());
sort(tArray.begin(), tArray.end());
Obviously, there is something about how overloaded cast operators work that I am ignorant of. Any ideas?
Thanks.
CONSTRAINTS:
I may not use a C++11 (so no std::array from C++11). I may not use begin() nor end().
Upvotes: 2
Views: 1945
Reputation: 9526
Your requirement that you may use begin()
nor end()
is problematic. Sort requires random access iterator; see Bjarne Stroustrup The C++ programming language 4th edition and std::sort
.
Using an explicit cast and pointer artithmic, you should be able to do the following:
For example let T
be std::string
, let N
be 42, and let b
an initialised Block<T,N>
:
Block<std::string, 42> b;
std::string* begin = (std::string*)b;
std::string* end = begin + 42; // Or if Block has Block.size()
// std::string* end = begin + b.size()
std::sort(begin, end);
Now b
contains the strings sorted according to bool operator<(const std::string&, const std::string&)
.
Upvotes: 1