Bitwise-shift operator with pointers and templates - Compiler Error

Started by
3 comments, last by deadimp 17 years, 9 months ago
I'm getting a compiler error that I do not know how to fix, and do not really understand why I'm getting it. Here's the basic code:
 template <typename T>
struct Test {
Test& operator<<(const T* &x) {
  printf(" << %d",*x);
  return *this;
 }
};
Test<int> test;
...
int a=2,b=3,c=4;
test << &a << &b << &c //I saw Qt using this style in their assistant...
And here's the error (MinGW): "no match for 'operator<<' in 'test << &a'" "candidates are: Test<T>& Test<T>::operator<<(const T*&) [with T = int] " It works fine if I have it simply copy the pointer in the operation, but I want to know what I'm doing wrong here...
Projects:> Thacmus - CMS (PHP 5, MySQL)Paused:> dgi> MegaMan X Crossfire
Advertisement
You want something like:
Test& operator<<( T const * const x ) {  printf(" << %d",*x);  return *this;}

- Passing x by reference is unnecessary.
- It was failing because the address-of operator returns a constant pointer.

[edit: You could also do it by reference, but the calling code would change:
Test& operator<<( T const &x ) {  printf(" << %d",x);  return *this;}// ...int a = 2, b = 3, c = 4;test << a << b << c;
]


jfl.
Haven't learned that syntax yet...
Can you break that down for me?

Also, thanks.
Projects:> Thacmus - CMS (PHP 5, MySQL)Paused:> dgi> MegaMan X Crossfire
Certainly. In C++, you essentially read types from right to left. So:

int * const is a const pointer to an int.
int const * is a pointer to a const int.
int const * const is a const pointer to a const int.
const int * and int const * are equivalent.
So are const int and int const.

Does that help?

Read my above edit, by the way. You may prefer that method.
Well, I decided not to make it constant because it conflicted with other functions, and dropped the referencing to a pointer, since it was only a pointer.
Plus, I'm going to add that other operator overload. Thanks!
Projects:> Thacmus - CMS (PHP 5, MySQL)Paused:> dgi> MegaMan X Crossfire

This topic is closed to new replies.

Advertisement