I have the following class
template<typename T>
class A
{
public:
A(T* d) : ptr(d)
{}
A(const T* d) : ptr(const_cast<T*>(d))
{}
T* Ptr()
{
static_assert(???, "Not allowed when using A(const T* d)");
return ptr;
}
const T* Ptr() const
{
return ptr;
}
private:
T* ptr;
}
How can I achieve that when Ptr() is compiled, I know which constructor was used to create this object? I want to statically assert that when Ptr() is compiled that the consstructor A(T* d) was used:
unsigned char* ptr = new unsigned char[10];
const unsigned char* cptr = new unsigned char[10];
A a(ptr);
A ca(cptr);
a.Ptr(); // Compiles
ca.Ptr(); // Gives compile error
I want to detect compile time if the programmer calls Ptr() when the object of class A was created using a const ptr. Calling Foo when created with const ptr is not allowed
I want to use it like this
void Foo(A<int>& r)
{
....
int* ptr = a.Ptr();
....
}
void Bar(const A<int>& r)
{
...
}
...
A a(ptr);
A ca(cptr);
Bar(a);
Bar(ac);
Foo(a);
Foo(ac);// Gives compile error