Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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.");

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
  }
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top