• Advertisement
Sign in to follow this  

Bitwise-shift operator with pointers and templates - Compiler Error

This topic is 4240 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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...

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Haven't learned that syntax yet...
Can you break that down for me?

Also, thanks.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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!

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement