Boost logo

Boost Users :

Subject: Re: [Boost-users] How to deduce (possibly void) return type of member function?
From: Terry Golubiewski (tjgolubi_at_[hidden])
Date: 2010-05-22 18:46:27


Mr. Kim Kuen Tang,

You are awesome! You approach worked! Thank you! However....

I want to detect the function return type of a user-supplied message
handler.
This non-generic version compiles and runs as expected.

#include <boost/mpl/identity.hpp>
#include <boost/typeof/typeof.hpp>

#include <cstddef>

struct MessageHandler1 {
  void f(const char*);
}; // MessageHandler1

struct MessageHandler2 {
  int f(const char*);
}; // MessageHandler2

template<class R, class T>
boost::mpl::identity<R> TypeDeducer(R (T::*)(const char*));

typedef BOOST_TYPEOF(TypeDeducer(&MessageHandler1::f))::type Type1;
typedef BOOST_TYPEOF(TypeDeducer(&MessageHandler2::f))::type Type2;

#include <iostream>
#include <iomanip>
#include <typeinfo>

using namespace std;

int main() {
  cout << typeid(Type1).name() << endl;
  cout << typeid(Type2).name() << endl;
} // main

But this generic version doesn't compile...

     1 #include <boost/mpl/identity.hpp>
     2 #include <boost/typeof/typeof.hpp>
     3
     4 #include <cstddef>
     5
     6 struct MessageHandler1 {
     7 void f(const char*);
     8 }; // MessageHandler1
     9
    10 struct MessageHandler2 {
    11 int f(const char*);
    12 }; // MessageHandler2
    13
    14 template<class R, class T>
    15 boost::mpl::identity<R> TypeDeducer(R (T::*)(const char*));
    16
    17 template<class T>
    18 struct GenericDeducer {
    19 typedef BOOST_TYPEOF_TPL(TypeDeducer(&T::f))::type type;
    20 }; // GenericDeducer
    21
    22 #include <iostream>
    23 #include <iomanip>
    24 #include <typeinfo>
    25
    26 using namespace std;
    27
    28 int main() {
    29 cout << typeid(GenericDeducer<MessageHandler1>::type).name() <<
endl;
    30 cout << typeid(GenericDeducer<MessageHandler2>::type).name() <<
endl;
    31 } // main

try3.cpp
using native typeof
try3.cpp(19) : error C2784: 'boost::mpl::identity<T> TypeDeducer(R
(__thiscall T::* )(const char *))' : could not deduce template argument for
'R (__thiscall T::* )(const char *)' from 'T::f'
        try3.cpp(15) : see declaration of 'TypeDeducer'
        try3.cpp(20) : see reference to class template instantiation
'GenericDeducer<T>' being compiled


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net