problem with "typeof" extension (C++)

Brian McNamara lorgon@cc.gatech.edu
Fri Apr 28 00:53:00 GMT 2000


I recently heard about the "typeof" extension your provide for C/C++.
This immediately struck me as undoubtedly the most useful language
extension ever.  However, I cannot get it to work.  :(

I couldn't find any documentation on "typeof" other than one "info" node
that didn't help me at all.

Here's the basic idea: I want to use typeof to discover an overloaded
(or template) function's return type, given only a set of arguments.  I
tried to make this C++ template:

   template <class F, class X>
   struct Ret1 {
      F f;
      X x;
      typedef typeof( f(x) ) type;
   };

but the compiler doesn't seem to like it.  Since I don't have the latest
version of g++, I tried running my code with last night's snapshot at
   http://www.codesourcery.com/gcc-compile.html  
but it still didn't compile.  I include my source code an the error
message below.

It may be the case that this is a "documentation bug" rather than a
"compiler bug"--that is, I may have simply misunderstood how you intend
"typeof" to be used.  If this is the case, let me _beg_ you to make
typeof work with the code below.  There are dozens of awesome things you
can do in C++ if only you could discover the return types of
function-templates.  The "typeof" operator (or something similar) is
something that the next revision of the C++ standard desperately needs.

Ok, enough whining, here's the code.  :)

----------------------------------------------------------------------
/*
Output from
   http://www.codesourcery.com/gcc-compile.html
is
     /tmp/@19813.1:18: invalid use of member `Ret1::x'
     /tmp/@19813.1:18: invalid use of member `Ret1::f'
     /tmp/@19813.1:18: confused by earlier errors, bailing out
*/

#include <iostream>

template <class F, class X>
struct Ret1 {
   F f;
   X x;
   typedef typeof( f(x) ) type;    // <--- so-called line 18
};

template <class F, class G>
class T_unary_compose {
   F f;
   G g;
public:
   T_unary_compose( const F& ff, const G& gg ) : f(ff), g(gg) {}
   template <class T>
   typename Ret1<F,typename Ret1<G,T>::type>::type
   operator()( T x ) const {
      return f(g(x));
   }
};

template <class F, class G>
T_unary_compose<F,G> compose( const F& f, const G& g ) {
   return T_unary_compose<F,G>( f, g );
}

struct Ident {
   template <class T>
   T operator()( T x ) const {
      return x;
   }
};

struct Zee {
   template <class T>
   char operator()( T ) const {
      return 'z';
   }
};

struct Pi {
   template <class T>
   double operator()( T ) const {
      return 3.14159265359;
   }
};

int main() {
   cout << compose( Ident(), Zee() )( 3 ) << endl;   // z
   cout << compose( Ident(), Pi() )( 3 ) << endl;    // 3.14159
   return 0;
}
----------------------------------------------------------------------
 

-- 
-Brian McNamara (lorgon@cc.gatech.edu), your friendly CS 2340 TA


More information about the Gcc-bugs mailing list