I have quite a few functions that take containers of pointers to const objects as arguments. I need to call these functions with containers of pointers to non-const objects. I seem to remember reading somewhere that this is not allowed. Is there a way to work around this other than writing 2 copies of the function?
Example(this code doesn't compile):
#include <vector>
#include <iostream>
using namespace std;
void fn(vector<const int *> par) {
cout<<"Function with const ptrs\n"<<endl;
}
int main()
{
vector<int *>v;
fn(v);
}
You could initialise a new vector.
#include <vector>
#include <iostream>
using namespace std;
void fn(vector<const int *> par) {
cout << "Function with const ptrs\n" << endl;
}
int main()
{
vector<int *>v;
fn(vector<const int *>(v.begin(), v.end()));
}
If it is an option, consider making your functions take ranges, for example something like:
template<typename t_iterator>
void fn(t_iterator beg_iter, t_iterator end_iter) {
for(; beg_iter != end_iter; ++beg_iter) {
// do something
}
}
This should operate over vector<int*>
and vector<const int*>
and also deque<int*>
etc
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.