Question

I want to specialize a template function declared as:

template<typename Type> Type read(std::istream& is);

I then have a lot of static implementations

static int read_integer(std::istream& is);

a.s.o. Now I'd like to do a macro so that specialization of read is as simple as:

SPECIALIZE_READ(read_integer)

So I figured I'd go the boost::function_traits way and declare SPECIALIZE_READ as:

#define SPECIALIZE_READ(read_function) \
   template<> boost::function_traits<read_function>::result_type read(std::istream& is) { \
      return read_function(is); \
   }

but VC++ (2008) compiler complains with: 'boost::function_traits' : 'read_integer' is not a valid template type argument for parameter 'Function'

Ideas ?

Was it helpful?

Solution

To my knowledge, there is no mechanism (other than decltype in C++0x) to obtain the return type from a function pointer, without passing that same function pointer as a parameter.

The easiest way is to accept the duplication of the return types:

#define SPECIALIZE_READ(type, read_function) \
   template<> type read(std::istream& is) { \
      return read_function(is); \
   }

SPECIALIZE_READ(int, read_integer)

OTHER TIPS

Maybe I am wrong but if I remember well what I've experienced during my C++ programming carrier, functions may not be overloaded by differing in the return type only. I guess the stuff will work if you do this:

template<typename Type> void read(std::istream& is, Type& objectToRead);

And use the Type as an argument. This has to do with the way compilers usually decorate c++ names if I recall well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top