Get address of const method - c++

I would like to be able to form a pointer-to-member type knowing only the class itself and method name. Unfortunately I am not able to do so having a const and non-const method variants in my class.
Example code snippet:
struct A
{
void method() {}
void method() const {}
};
int main()
{
decltype(&A::method) _;
}
I have also tried the following this but without much success either:
decltype(&(std::declval<const A>().method)) _;
Both approaches fail as decltype cannot resolve this due to ambiguity:
'decltype cannot resolve address of overloaded function'
How can I achieve this in some other way?

You can do it like this:
struct A
{
void method() {
cout << "Non const\n";
}
void method() const {
cout << "const function\n";
}
};
int main()
{
typedef void (A::*method_const)() const;
method_const a = &A::method; //address of const method
typedef void (A::*method_nonconst)();
method_nonconst b = &A::method; //address of non const method
A var;
std::invoke(a, var);
std::invoke(b, var);
}
If you want to use decltype() to achieve the same thing, you first have to manually select the function you want using static_cast<>:
int main()
{
//const
decltype( static_cast <void (A::*)() const> (&A::method) ) a;
//non const
decltype( static_cast <void (A::*)()> (&A::method) ) b;
a = &A::method;
b = &A::method;
A var;
std::invoke(a, var);
std::invoke(b, var);
}
Live on Coliru

Related

std::function incomplete type on const function

Consider the following code which works as expected:
#include <iostream>
#include <functional>
struct foo
{
std::function<int()> get;
};
struct bar
{
int get()
{
return 42;
}
};
int main()
{
foo f;
bar b;
f.get = std::bind(&bar::get, &b);
if (f.get())
std::cout << "f.get(): " << f.get() << std::endl;
return 0;
}
Now, let's assume that bar::get() is a const member function:
#include <iostream>
#include <functional>
struct foo
{
std::function<int()const> get;
};
struct bar
{
int get() const
{
return 42;
}
};
int main()
{
foo f;
bar b;
f.get = std::bind(&bar::get, &b);
if (f.get())
std::cout << "f.get(): " << f.get() << std::endl;
}
Using GCC 9.2, this snipped throws the following compiler error:
main.cpp:6:31: error: field 'get' has incomplete type 'std::function<int() const>'
6 | std::function<int()const> get;
| ^~~
In file included from /usr/local/include/c++/9.2.0/functional:59,
from main.cpp:2:
/usr/local/include/c++/9.2.0/bits/std_function.h:128:11: note: declaration of 'class std::function<int() const>'
128 | class function;
| ^~~~~~~~
I fail to understand why foo::get has incomplete type.
Could somebody point me towards the right direction for understanding this behavior and "fixing" it accordingly?
I have the need to bind a const member function to a function pointer.
int()const is an abominable type.
std::function<int()const> is not a type, because it doesn't match the only defined specialisation
namespace std {
template< class R, class... Args >
class function<R(Args...)> { ... };
}
Just use std::function<int()>.
The const bit only makes sense for member functions. You've already bound bar::get to an instance b to save it as a std::function.
As mentioned by #KamilCuk:
The constness is checked at std::bind, not at std::function
You don't need to pass explicit const to std::function. Just use your older prototype: std::function<int()>. It will work if you don't have const overload (that mean, you have either one of these int bar::get() or int bar::get() const) for the same member function (Otherwise, you need to type cast explicity).
Actually, your function (int bar::get() const) will be having a signature like this (behind the scenes):
// int bar::get() const
int get(const bar *const this)
{
return 42;
}
// int bar::get()
int get(bar *const this)
{
return 42;
}
If you have overloads and want to bind specific member function, you can do something like this:
typedef int(bar::*fptr)(void) const; // or remove const
std::bind((fptr)&bar::get, &b );
See this:
#include <iostream>
#include <functional>
#include <vector>
struct foo
{
std::function<int()> get;
};
struct bar
{
int get()
{
return 42;
}
int get() const
{
return 50;
}
};
int main()
{
foo f;
bar b;
typedef int (bar::*fptr)(void);
typedef int (bar::*fcptr)(void) const;
f.get = std::bind((fptr)&bar::get, &b);
if (f.get())
std::cout << "f.get(): " << f.get() << std::endl;
f.get = std::bind((fcptr)&bar::get, &b);
if (f.get())
std::cout << "f.get(): " << f.get() << std::endl;
}
Output:
f.get(): 42
f.get(): 50
std::bind does not pass through constness to the callable. Therefore, the following would work:
struct foo {
std::function<int()> get;
// ^ note there is no 'const'
};

Polymorphic casting from void*

See code below for the details, but the underlying scenario is as follows. I have a container (a session) that I can place objects in and pull out from.
Similar to:
std::shared_ptr<Tiger> t = ...;
session.store("tigers/1", t);
std::shared_ptr<Tiger> t2 = session.load<Tiger>("tigers/1");
With both functions defined as:
class Session {
template<class T>
void store(std::string id, std::shared_ptr<T> instance);
template<class T>
std::shared_ptr<T> load(std::string id);
}
Note that a session can store heterogeneous types, but at store and load time I statically known what the type of the variable is.
My problem is that I run into a situation where the user wants to put a Tiger into the session but checks out a base type, instead. For example:
session.load<Animal>("tigers/1");
Right now, I'm effectively storing the data as void* inside the session and use reinterpret_cast to get them back to the user provided type. This... works, as long as everything is trivial, but when we get to a slightly more complex situation, we run into issues.
Here is the full code demonstrating my issue:
struct Animal
{
virtual void Pet() const = 0;
};
struct IJumpable
{
virtual void Jump() const = 0;
};
struct Tiger : Animal, IJumpable
{
void Pet() const override
{
std::cout << "Pet\n";
}
void Jump() const override
{
std::cout << "Jump\n";
}
};
int main()
{
auto cat = std::make_shared<Tiger>();
// how the data is stored inside the session
auto any_ptr = std::static_pointer_cast<void>(cat);
// how we get the data out of the session
auto namable = std::static_pointer_cast<IJumpable>(any_ptr);
namable->Jump();
std::cout << std::endl;
}
If you run this code, you'll see that it runs, but instead of calling Jump, it calls to Pet. I understand that this is because of the wrong virtual method table being used, since I'm effectively calling reinterpret_cast on `void*.
My question is if there is a good way to handle this scenario in C++. I've looked around and didn't see anything that matches what I need.
Everything I found about heterogeneous containers always assumed a shared base class, which I don't have nor want. Is this possible?
You could make the user provide you with the correct casting trek to follow:
class Session {
template<class T>
void store(std::string id, std::shared_ptr<T> instance);
template<class T>
std::shared_ptr<T> load(std::string id);
template<class Stored, class Retrieved>
std::shared_ptr<Retrieved> load_as(std::string id) {
auto stored = load<Stored>(id);
return std::static_pointer_cast<Retrieved>(stored);
}
}
This makes a messy usage at the caller site, but the information must come from somewhere:
auto shere_khan = make_shared<Tiger>();
session.store("tigers/1", shere_khan);
auto bagheera = session.load_as<Tiger, IJumpable>("tigers/1");
Solution courtesy of my brother who happens to be a C++ expert with no stackoverflow :)
Here is a void_ptr implementation that enables polymorphic casting using exception handling to discover types. The performance should be close to that of a dynamic_cast. You should be able to optimize the above using std::type_index and caching the offsets.
#include <stdio.h>
class void_ptr {
void* obj;
void (*discover_type)(void*);
template<typename T>
static void throw_typed_object(void* obj)
{
T* t = static_cast<T*>(obj);
throw t;
}
public:
void_ptr() : obj(0) {}
template<typename T>
void_ptr(T* t) : obj(t), discover_type(throw_typed_object<T>)
{
}
template<typename T>
T* cast() const
{
try {
discover_type(obj);
} catch(T* t) {
return t;
} catch(...) {
}
return 0;
}
};
struct Animal {
virtual ~Animal() {}
virtual const char* name() { return "Animal"; }
};
struct Speaker {
virtual ~Speaker() {}
virtual const char* speak() { return "hello"; }
};
struct Lion : public Animal, public Speaker {
virtual const char* name() { return "Lion"; }
virtual const char* speak() { return "Roar"; }
};
int main()
{
void_ptr ptr(new Lion());
Animal* a = ptr.cast<Animal>();
Speaker* s = ptr.cast<Speaker>();
printf("%s\n", a->name());
printf("%s\n", s->speak());
}
IMO best solution is not to cast to pointer to void but to other type which can be dynamic sidecast to required type.
#include <iostream>
#include <memory>
struct Animal
{
virtual ~Animal() {}
virtual void Pet() const = 0;
};
struct IJumpable
{
virtual ~IJumpable() {}
virtual void Jump() const = 0;
};
struct IStrorable
{
virtual ~IStrorable() {}
};
struct Tiger : Animal, IJumpable, IStrorable
{
void Pet() const override
{
std::cout << "Pet\n";
}
void Jump() const override
{
std::cout << "Jump\n";
}
};
int main()
{
auto cat = std::make_shared<Tiger>();
auto any_ptr = std::static_pointer_cast<IStrorable>(cat);
auto namable = std::dynamic_pointer_cast<IJumpable>(any_ptr);
namable->Jump();
std::cout << std::endl;
}
Live example
Other solutions require use of std::any, but this will be less handy.
It is a bit disturbing that your method load is a template.

How can I detect if the instance is const from a member function?

I would like to write a member function which detects if the instantiated object is const.
To give a simple example, we can consider the following class definition
class Foo{
public:
void constnessChecker(){
bool isConst;
// MORE CODE GOES HERE...
if (isConst) {
std::cout << "This instance is const! << std::endl;
} else {
std::cout << "This instance is not const! << std::endl;
}
}
};
and the following code
int main(){
Foo foo1;
Foo const foo2;
foo1.constnessChecker();
foo2.constnessChecker();
}
which should produce
This instance is not const!
This instance is const!
Is this possible?
Provide const and non-const overloads:
class Foo
{
public:
void constnessChecker(){
std::cout << "This instance is not const\n";
}
void constnessChecker() const {
std::cout << "This instance is const\n";
}
....
};
In the style of boost::is_const or std::is_const, you can also write up the following:
#include <iostream>
template <typename T>
struct is_const
{
static const bool value = false;
};
template <typename T>
struct is_const<const T*>
{
static const bool value = true;
};
struct S
{
void f() const
{
std::cout << is_const<decltype(this)>::value << std::endl;
}
void f()
{
std::cout << is_const<decltype(this)>::value << std::endl;
}
int m;
};
int main(int argc, char** argv)
{
const S& cs = S(); // note that choosing a const-ref is merely to force the compiler to choos S::f() const!
cs.f (); // prints 1
S().f (); // prints 0
return 0;
}
I haven't looked at the implementation of std::is_const but for some reason it returns false where the above is_const returns true.
Note: Obviously you need support for decltype and thus the above will only work for C++11 compliant compilers.

Call different versions of template member function based on template paramaters

I need to call different versions of a template member function with the same arguments based on certain static members of the template parameters. Here's a sort of simplified version of what I need to do:
class A {
public:
//...
static const char fooString[];
};
const char A::fooString[] = "This is a Foo.";
class B {
public:
//...
static const char barString[];
};
const char B::barString[] = "This is a Bar.";
class C {
public:
//...
static const char fooString[];
};
const char C::fooString[] = "This is also a Foo.";
//Many other classes which have either a fooString or a barString
void doFoo(const char*s) { /*something*/ }
void doBar(const char*s) { /*something else*/ }
template&ltclass T>
class Something {
public:
//This version should be called if T has a static member called "fooString",
//so it should be called if T is either class A or C
void doSomething() { doFoo(T::fooString); }
//This version should be called if T has a static member called "barString",
//so it should be called if T is class B
void doSomething() { doBar(T::barString); }
};
void someFunc()
{
Something&ltA> a;
Something&ltB> b;
Something&ltC> c;
a.doSomething(); //should call doFoo(A::fooString)
b.doSomething(); //should call doBar(B::barString)
c.doSomething(); //should call doFoo(C::fooString)
}
How would I achieve this?
A possible solution:
#include <iostream>
#include <type_traits>
class A {
public:
//...
static const char fooString[];
};
const char A::fooString[] = "This is a Foo.";
class B {
public:
//...
static const char barString[];
};
const char B::barString[] = "This is a Bar.";
class C {
public:
//...
static const char fooString[];
};
const char C::fooString[] = "This is also a Foo.";
void doFoo(const char*s) { std::cout << "doFoo: " << s << "\n"; }
void doBar(const char*s) { std::cout << "doBar: " << s << "\n"; }
template<class T>
class Something {
public:
//This version should be called if T has a static member called "fooString",
//so it should be called if T is either class A or C
template <typename TT = T, typename std::enable_if<TT::fooString != 0, bool>::type = false>
void doSomething() { doFoo(T::fooString); }
//This version should be called if T has a static member called "barString",
//so it should be called if T is class B
template <typename TT = T, typename std::enable_if<TT::barString != 0, bool>::type = false>
void doSomething() { doBar(T::barString); }
};
int main()
{
Something<A> a;
Something<B> b;
Something<C> c;
a.doSomething(); //should call doFoo(A::fooString)
b.doSomething(); //should call doBar(B::barString)
c.doSomething(); //should call doFoo(C::fooString)
}
Output:
doFoo: This is a Foo.
doBar: This is a Bar.
doFoo: This is also a Foo.

pointer to const member function typedef

I know it's possible to separate to create a pointer to member function like this
struct K { void func() {} };
typedef void FuncType();
typedef FuncType K::* MemFuncType;
MemFuncType pF = &K::func;
Is there similar way to construct a pointer to a const function? I've tried adding const in various places with no success. I've played around with gcc some and if you do template deduction on something like
template <typename Sig, typename Klass>
void deduce(Sig Klass::*);
It will show Sig with as a function signature with const just tacked on the end. If to do this in code it will complain that you can't have qualifiers on a function type. Seems like it should be possible somehow because the deduction works.
You want this:
typedef void (K::*MemFuncType)() const;
If you want to still base MemFuncType on FuncType, you need to change FuncType:
typedef void FuncType() const;
typedef FuncType K::* MemFuncType;
A slight refinement showing how to do it without a typedef.
In a deduced context like the following, you can't use a typedef.
template <typename Class, typename Field>
Field extract_field(const Class& obj, Field (Class::*getter)() const)
{
return (obj.*getter)();
}
applied to some class with a const getter:
class Foo {
public:
int get_int() const;
};
Foo obj;
int sz = extract_field(obj, &Foo::get_int);
Another more direct way to do it (avoiding using and typedefs) is this:
#include <iostream>
class Object
{
int i_;
public:
int j_;
Object()
: Object(0,0)
{}
Object(int i, int j)
: i_(i),
j_(j)
{}
void printIplusJplusArgConst(int arg) const
{
std::cout << i_ + j_ + arg << '\n';
}
};
int main(void)
{
void (Object::*mpc)(int) const = &Object::printIplusJplusArgConst;
Object o{1,2};
(o.*mpc)(3); // prints 6
return 0;
}
mpc is a const method pointer to Object.