I would like to use some memory on the stack to store some objects (it arises in a small vector optimization library). Therefore, my class is
template <typename T, int n>
class SmallVector {
private:
T* begin_;
T* end_;
T* capacity_;
alignas(T) char data_small_[n * sizeof(T)];
public:
...
}
To check if the small_data_ buffer is used, I define the function
bool is_data_small_used() const {
return begin_ == reinterpret_cast<T*>(data_small_);
}
Unfortunately, it does not work. Clang version
Apple LLVM version 6.0 (clang-600.0.56) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin14.1.0
Thread model: posix
gives me the following error message:
./il/container/SmallVector.h:44:25: error: reinterpret_cast from 'const char *' to 'il::Vector<double> *' casts away qualifiers
return begin_ == reinterpret_cast<T*>(data_small_);
and the Intel compiler says the same. The only solution I found is to do
begin_ == (T*) data_small_
which is not very C++. Is there a "correct way" to do this in C++?
The error message suggests that the problem is occurring inside a const
member function. In that situation, this
is considered to point to a const object, so data_small_
will have type const char[N]
.
A simple fix would be to write:
return begin_ == reinterpret_cast<T const *>(data_small_);
and another one would be:
return reinterpret_cast<char const *>(begin_) == data_small_;
The C-style cast worked because that cast can do a reinterpret_cast
and a const_cast
together, whereas a reinterpret_cast
by itself cannot cast away const
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments