Reference to class method - function

I would like to pass to a function a reference to a class method.
For example:
#include <functional>
struct Foo
{
int f(const int& val) const
{
return val+2;
}
};
int caller(const std::function<int(const int&)>& f)
{
return f(1);
}
int main()
{
caller([](const int& val){return val+2;}); // OK
Foo foo;
caller(foo.f); // WRONG
return 0;
}
How can I fix the second call of caller() (NB: Foo:f() is not static)?

In your case, function f doesn't use any member of Foo so it can be declared static
static int f(const int& val)
and passed as:
caller(&Foo::f);
But suppose that f cannot be declared static and you want to pass "reference" to member function of particular object.
You can use lambda in that case:
Foo foo;
caller(
[&foo](const int& val){
return foo.f(val);
}
);
foo object is captured in square brackets (in this case by reference) so that you can call f member function on that particular object.
Although it is not part of your question, I should add that it is not really useful to pass int by const reference, as you will not gain any performance improvement that way. Actually, your code will run slower than if you pass int by value.

Related

Dart - declare function as variable

In Dart - as in many other languages - there is more than one way to declare a function. The question is, are there any differences aka "when should I use which"?
void foo(int i) {
print('i = $i');
}
void main() {
void Function(int) bar = (int j) {
print('j = $j');
};
foo(1);
bar(2);
}
Is there any difference in the declaration of foo or bar other than the fact that bar can be overwritten?
Functions can be introduced by
function declarations
method decla-rations
getter declarations
setter declarations
constructor declarations
function literals
In terms of Dart specification there is 2 differences between function literals (aka anonymous function) and other declarations
it has no name - anonymous
we can't declare a return type (which only obtained by means of type inference)
If you prefer to keep type safety, you will have to write long declaration.
Consider this example:
String foo(int i, {bool b}) => '$b $i'; // return type declared
final bar = (int i, {bool b}) => '$b $i'; // return type could not be infered
final String Function(int i, {bool b}) bar = (i, {b}) => '$b $i'; // return type infered
From my perspective
bar isn't as readable as foo declaration
Let functions literals do their anonymous job =)
PS If I missed anything - please edit my answer or reach me in comments

Custom SWIG Wrapping to Handle Nested C Structures

I have the below C struct that has a couple nested structures that have proven to be difficult to deal with using my knowledge of SWIG. Everything below is easily wrapped by SWIG execept for saddr (C socket address) and mac[6] (C array representing a MAC address). Since SWIG gives me the pointer value (SWIGTYPE_p_unsigned_char and SWIGTYPE_p_sockaddr), I would like to somehow call a helper C function to convert the pointer to a char*. I have the helper function, but I don't know the best way to plug this into SWIG. Is there any way to configure the getMac() and getSaddr() to call the helper function?
C Structure Trying To Wrap:
%rename (Details) details_t_;
typedef struct details_t_ {
uint16_t code;
char *name;
**sockaddr *saddr;**
uint32_t saddr_len;
uint8_t flag;
ios_boolean is_child;
**unsigned char mac[6];**
} details_t;
Generated Java Code:
public void setMac(SWIGTYPE_p_unsigned_char value) {
TestJNI.Details_mac_set(swigCPtr, this, SWIGTYPE_p_unsigned_char.getCPtr(value));
}
public SWIGTYPE_p_unsigned_char getMac() {
long cPtr = TestJNI.Details_mac_get(swigCPtr, this);
return (cPtr == 0) ? null : new SWIGTYPE_p_unsigned_char(cPtr, false);
}
public void setSaddr(SWIGTYPE_p_sockaddr value) {
TestJNI.Details_saddr_set(swigCPtr, this, SWIGTYPE_p_sockaddr.getCPtr(value));
}
public SWIGTYPE_p_sockaddr getSaddr() {
long cPtr = TestJNI.Details_saddr_get(swigCPtr, this);
return (cPtr == 0) ? null : new SWIGTYPE_p_sockaddr(cPtr, false);
}
Proposed SWIG.i Changes:
%module Test
%rename (realId) details_t_::mac;
%typemap(javacode) struct details_t_ %{
public String getMac() {
return Test.getMacAddressAsString(this);
//this is a pointer to details_t_ struct
}
%};
%rename (Details) details_t_;
typedef struct details_t_ {
uint16_t code;
char *name;
**sockaddr *saddr;**
uint32_t saddr_len;
uint8_t flag;
ios_boolean is_child;
**unsigned char mac[6];**
} details_t;
You can do this with a javacode typemap, e.g.:
%module test
%rename (realId) Sample::id;
%typemap(javacode) struct Sample %{
public byte getId() {
return 100-getRealId(); // Transform the real call
}
public void setId(byte value) {
setRealId(value+100);
}
%};
struct Sample {
char id;
};
Renames the generated getId() and setId(), but provides a Java get/set which can be written in terms of the SWIG generated (but renamed) one. You might want to make the SWIG generated ones private though.

stl remove_if with class member function result

I have a object container, list; and class Foo have a member function id() return an integer identifier.
Now I want to use stl algorithm remove_if to remove some objects whose id is less than a value.
I don't want to provide a function for id compare, If it is possible for me to write one line code with STL but boost to implement it.
class Foo{
public:
unsigned id() const {return id_;}
...
private:
unsigned id_
...
};
list<Foo> foo_list;
std::remove_if(foo_list.begin(), foo_list.end(), ???);
If STL can do this with only std::bind2nd, stl::less(), std::mem_fun_ref() or other stl functions.
Yes, that is possible to achieve without lambdas, if you agree to change the interface of Foo a little bit.
class Foo
{
public:
Foo(unsigned id)
: id_(id) {}
bool is_equal(unsigned id) const
{ return id_ == id; }
private:
unsigned id_;
};
typedef list<Foo> FooList;
FooList foo_list;
foo_list.push_back(Foo(1));
foo_list.push_back(Foo(2));
unsigned to_remove = 1;
foo_list.remove_if(std::bind2nd(std::mem_fun_ref(&Foo::is_equal), to_remove));

In C++, how to use find_if on a map with a functor when keys are struct with strings?

I have a stl::map which key type is a custom struct. I want to know if this map already has a key with a specific string as component (noted as "id" below), whatever the value of its other components. Inspired by this answer and this one also, I try to use stl::find_if with a custom functor:
map<myStruct, vector<size_t> > myMap;
struct myStruct
{
string a, b, c, id;
};
struct checkId : unary_function<pair<myStruct, vector<size_t> >, bool>
{
private:
string _exp;
public:
checkId (myStruct x) : _exp(x.id) {}
bool operator() (const pair<myStruct, vector<size_t> > & p) const
{
return p.first.id.compare(_exp) == 0;
}
};
map<myStruct, vector<size_t> >::iterator it;
myStruct newS; // to be initialized, but not shown here
it_mP2P = find_if(myMap.begin(), myMap.end(), checkId(newS));
When I compile this, gcc returns me:
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_function.h: In member function ‘bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = myStruct]’:
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_map.h:347: instantiated from ‘_Tp& std::map<_Key,_Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = myStruct, _Tp = std::vector<long unsigned int, std::allocator<long unsigned int> >, _Compare = std::less<myStruct>, _Alloc = std::allocator<std::pair<const myStruct, std::vector<long unsigned int, std::allocator<long unsigned int> > > >]’
myprogram.cpp:386: instantiated from here
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_function.h:227: error: no match for ‘operator<’ in ‘__x < __y’
Does this mean that I have to overload the operator "<" to work with my custom struct if I want to use my functor "checkId"? How can I do this? I am not a C++ expert,so thanks in advance for any piece of code.
http://codepad.org/VYNqdZeF
struct myStruct
{
std::string a, b, c, id;
bool operator<(const myStruct& rhs) const //HERES THE MAGIC
{return id < rhs.id;} //WHEEEEEEEEEEEE!
};
This is required to make std::map<myStruct, stuff> work, without passing a custom comparison functor.
It's got nothing to do with checkId. The following demonstrates the same problem:
map<myStruct, vector<size_t> > myMap;
struct myStruct
{
string a, b, c, id;
};
std::map is a sorted map (it's usually implemented as a binary search tree)... the key type (myStruct in this case) must have operator< implemented simply to construct the map.
If you don't need fast lookups, you can just use a vector< pair< myStruct, vector<size_t> > >; if you need fast lookups, you have to add some kind of structure to myStruct. For a std::map this must be a comparison operator; alternatively you can use a std::unordered_map (in C++11; this is usually implemented as a hash table) -- in this case you will need to implement a hash function.
See the documentation of std::map and std::unordered_map for more details.
This has nothing to do with your use of find_if.
For a type to be a key of a map, it needs to be comparable, either by implementing operator< or by providing a comparator as a template parameter of the map.
Mooing Duck's answer is the easiest to do, but not the most flexible
if you go and write
struct myStruct
{
std::string a, b, c, id;
bool operator<(const myStruct& rhs) const
{return id < rhs.id;}
};
then all your maps that have myStruct as a key, will have to be sorted
by id.
Suppose you have one map that needs to be compared by a, and another one by b. If you put operator<() inside your myStruct, then you will have coupled the struct with its users, tightly, which is not good programming practice.
Instead, you could set a compare function to each map:
struct myStruct
{
std::string a, b, c, id; // keep your struct unchanged, and independent of clients
};
bool Compare_by_a(const myStruct &s1, const myStruct& s2) {
return s1.a < s2.a;
}
bool Compare_by_b(const myStruct &s1, const myStruct& s2) {
return s1.b < s2.b;
}
bool Compare_by_id(const myStruct &s1, const myStruct& s2) {
return s1.id < s2.id;
}
map<myStruct, vector<size_t>, Compare_by_a > map1;
map<myStruct, vector<size_t>, Compare_by_b > map2;
map<myStruct, vector<size_t>, Compare_by_id > map3;

Custom STL Containers

I have written code that allows one to traverse mapped data in the order it was entered.
The solution I coded a couple of times was:
Given a keytype, K, and and data type, D,
std::map
std::vector
When one wanted to randomly find a data entry, use map.find(K). When one wanted to traverse the map in entry order, use std::vector::iterator (begin(), end()].
This was fine, but as an exercise, I wanted to write this 'OrderedMap' as an STL compliant container. I also have (stripped down to this discussion):
template <typename K, typename D>
class OrderedMapValue
{
private:
K first_ref;
std::map<K,size_t>& m;
std::vector<D>& v;
public:
const K& first
D& second
assignment operator=(const D& data)
{
std::map<K,size_t>::const_iterator iter = m.find(first_ref);
v[iter.second] = data; // error checking of iter stripped
}
};
Further assuming
template <typename K, typename D>
class OrderedMap
{
public:
typename OrderedMapValue<K,D>& OrderedMap<K,D>::operator[](const K&);
// snip...
};
class MyClass
{
public:
MyClass(std::string s) : _my_data(s) {}
private:
std::string _my_data;
};
The following code works:
OrderedMap<std::string,MyClass*> omap;
omap["MyKey"] = new MyClass("dummy");
However, this code does not:
OrderedMap::iterator iter = omap.find("MyKey");
MyClass * obj = iter->second;
delete obj;
iter->second = new MyClass("dummy");
Assuming I have done something
a) Structurally silly or
b) Unnecessarily complex, how should this be done?
I realize that I'm likely reinventing the wheel here, but again, this effort is mainly to increase my knowledge of STL containers, their design patterns and proper use.
Thanks in advance for any insights,
I don't have a compiler right now to test this, so there could be errors, but I think you want it more like:
template <typename K, typename D>
class OrderedMap
{
private:
std::map<K,size_t> &m;
std::vector<D> &v;
public:
typename pair<K,D> TYPE;
TYPE& operator[](const K &k)
{
return v[ m[ k ]];
}
TYPE& operator[](size_t idx)
{
return v[ idx ];
}
pair<iterator,bool> insert( const TYPE& pair )
{
map<K, size_t>::const_iterator iter;
iter = m.find( pair.first );
if( iter != m.end() )
return make_pair( v[ iter.second], false );
m.insert( make_pair( pair->first, v.size() ));
v.push_back( pair->second );
return make_pair( v.last() , inserted );
}
iterator &begin()
{
return v.begin();
}
// etc
};
In OrderedMapValue::operator=, you have:
std::map<K,size_t>::const_iterator iter = m.find(first_ref);
What is first_ref? The code doesn't reference it (no pun intended) elsewhere. It looks to me like it might be a vestige from an older implementation, replaced elsewhere by the public member
const K& first.
Could this be the problem?
EDIT from the comments: The code doesn't show that first_ref is initialized anywhere; so for all I can tell, the call to m.find(first_ref) is searching for an empty string, rather than the key for the OrderedMapValue.