0

I have an overloaded operator& for my class where I do a static assert if the parameter is a pointer.

class test {
public:

  template<typename T>
  friend inline test& operator&(test& so, T const& t) {
    std::cout << "is_pointer : " << std::is_pointer<T>::value << std::endl;
    static_assert(std::is_pointer<T>::value, "no operator overloaded for pointers.");
    
    // some stuff
  }
};

If I use this operator I always get the assertion even if the type is definitively not a pointer. std::cout << "is_pointer : " << std::is_pointer<T>::value << std::endl; is printing a zero...

int main() {
  test t;
  t & 123;
  return 0;
}

Example.

user1810087
  • 5,146
  • 1
  • 41
  • 76
  • Quick hint for printing booleans: `std::cout << std::boolalpha;` before you do it. – pmr Nov 03 '13 at 19:29

3 Answers3

4

Of course the assertion fails. You're requiring that the type T is a pointer, but T here is an int.

Perhaps you meant the following?

// Ensure that `T` is not a pointer
static_assert(!std::is_pointer<T>::value, "no operator overloaded for pointers");

Assertions are statements that ensure a particular condition. It's not quite "if X then output error message Y"; in fact, it's the exact opposite. :)

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
2

You are asserting that the type passed is a pointer. If you pass something which is not a pointer, the static_assert() fails and you get a message. It seems, you want to precisely negate the condition as you do not want to work with pointers:

static_assert(!std::is_pointer<T>::value, "no operator overloaded for pointers.");
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
0

It sounds like you want this to compile if and only if T is not a pointer. In your original expression, you assert that T is a pointer.

Basically, the static_assert means, "My first argument better be true, otherwise I will complain at compile time with the second argument as error message."

What you seem to want:

class test {
public:

  template<typename T>
  friend inline test& operator&(test& so, T const& t) {
    static_assert(! std::is_pointer<T>::value, "no operator overloaded for pointers.");

    // some stuff
  }
};
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
NicholasM
  • 4,557
  • 1
  • 20
  • 47
  • 1
    `I can't comment, so I have to answer instead.` Actually the intention is that you don't comment _at all_ until you have the required rep, rather than going against the rules and finding any old inappropriate place to post your words. I'll let you off though, because this is a good answer and actually is an answer. :) – Lightness Races in Orbit Nov 03 '13 at 19:34