I would like to extend a base class which has a virtual function that takes a pointer to an array of a type. The derived class is more complex and could take advantage of multiple pointers to an array of that type.
derived
and other
开发者_如何学Python show different solutions to deals with that problem, but I dislike both of them. Is there anything I could do instead?
struct base {
virtual void set(int* p, std::size_t n) { }
};
struct derived : base
{
virtual void set(int* p, std::size_t n)
{
int** pp = new int*[1]; // must be deleted before destruction
pp[0] = p;
set(1, pp, n);
}
void set(std::size_t count, int* const* pp, std::size_t n)
{
}
};
struct other : base
{
virtual void set(int* p, std::size_t n)
{
m_helper[0] = p;
set(1, m_helper, n);
}
void set(std::size_t count, int* const* pp, std::size_t n)
{
}
private:
int* m_helper[1];
};
Theoretically, if you don't want to save the pointer itself, this should do:
virtual void set(int* p, std::size_t n)
{
set(1, &p, n);
}
void set(std::size_t count, int* const* pp, std::size_t n)
{
}
The code doesn't say anything about the goal which you want to achieve, as every function is almost empty. So I cannot suggest anything better than to use the following:
- Use
std::vector<int>
where you want to useint*
- Use
std::vector<std::vector<int> >
where you want to useint**
You could use variable argument lists:
void set(std::size_t count, std::size_t n, ...) {
va_list v;
va_start(v, n);
for (int i = 0; i < count; i++)
{
int* value = va_arg(vl, int*);
// ...
}
va_end(v);
}
精彩评论