Should static_assert really succeed when testing existence of an operator that's declared but not defined?

StackOverflow https://stackoverflow.com/questions/17368477

Question

Why does the static_assert below succeed? I have only made the << operator a friend, but I haven't created it anywhere.

struct foo {
  friend std::ostream &operator<<(std::ostream &stream, const foo &f);
};

template<typename T>
struct bar {
  //succeeds:
  static_assert(boost::has_left_shift<std::ostream,T>::value, "failure");
};

int main(int,char**) {
  bar<foo> b;
  return 0;
}
Was it helpful?

Solution

The friend declaration establishes that the operator exists. If you used it, the compiler would accept it:

std::cout << foo();

That's all the assertion can test, either. A program with this statement in it probably will not link because you haven't defined the operator, but just like the compiler, the assertion cannot detect that. It has no idea whether some other translation unit might eventually provide a definition for that function.

Compiling and linking are separate phases.

If you do provide a definition in another file, and you compile that file, you can then link the two compiled files together to form a complete program. You won't have to recompile the first file. That's what separate compilation is all about.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top