template mem fun problem gcc-3.0.2

Kayvan A. Sylvan kayvan@sylvan.com
Fri Feb 1 11:08:00 GMT 2002


On Fri, Feb 01, 2002 at 01:27:15PM -0500, Neal D. Becker wrote:
> >>>>> "Paolo" == Paolo Carlini <pcarlini@unitus.it> writes:
> 
>     >> This code gives a syntax error.  I think it should not.
>     Paolo> ... and what should give instead, in your opinion??
> 
> I may be mistaken, but I thought that the for a template function
> 
> template<typename T, typename W>
> T f (W);
> 
> You say:
> 
> X x = f<X> (w) in order to specify the particular template

No, it's not correct.

The compiler will correctly instantiate the template based on
the types you feed it.

For a template class, the compiler can not do that, so you must
give it the information.

Look at this example with a stripped down user-defined Rational number
class:

  #include <iostream>
  
  template <typename T>
  const T my_double(T& x)
  {
    return (x * 2);
  }
  
  // Incomplete Rational class. For testing only.
  //
  class Rational {
  public:
    Rational(int n = 0, int d = 1) : num(n), denom(d) {}; // Default constructor
    Rational(const Rational& r) : num(r.num), denom(r.denom) {}; // Copy ctor
    ~Rational() {}; // Destructor
    Rational operator*(int x) { // Multiply by int
      Rational res(*this);
      res.num *= x;
      return res;
    }
  private:
    int num, denom; // numerator and denominator
  
  friend ostream& operator<<(ostream&, const Rational&);
  };
  
  ostream& operator<<(ostream& c, const Rational& r)
  {
    return (c << r.num << "/" << r.denom);
  }
  
  int main()
  {
    int x = 6;
    float y = 7.77;
    Rational r(4, 17); // rational number 4/17
  
    std::cout << "double of " << x << " = " << my_double(x) << std::endl;
    std::cout << "double of " << y << " = " << my_double(y) << std::endl;
    std::cout << "double of " << r << " = " << my_double(r) << std::endl;
  
    return 0;
  }

This prints out:

  double of 6 = 12
  double of 7.77 = 15.54
  double of 4/17 = 8/17

The compiler simply instantiates the right my_double function.

			---Kayvan

[[ Available for consulting. http://www.sylvan.com/~kayvan/Resume.html ]]
-- 
Kayvan A. Sylvan          | Proud husband of       | Father to my kids:
Sylvan Associates, Inc.   | Laura Isabella Sylvan  | Katherine Yelena (8/8/89)
http://sylvan.com/~kayvan | "crown of her husband" | Robin Gregory (2/28/92)
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 232 bytes
Desc: not available
URL: <https://gcc.gnu.org/pipermail/gcc-help/attachments/20020201/deb90e10/attachment-0001.sig>


More information about the Gcc-help mailing list