Question

I tried this program with GCC and Clang, but both output nothing

#include <iostream>

struct A {
  A(){}

  template<typename T>
  A(T &) {
    std::cout << "copied!";
  }
};

void f(...) { }

int main() {
  A a;
  f(a);
}

According to my Standards reading, this program should output "copied!". Can anyone tell me whether I am mistaken or whether this is a bug in those two compilers?

No correct solution

OTHER TIPS

It would seem that what you expect is the behavior defined by the standard.

Template functions do not prevent the creation of copy constructors/assignment operators. So template functions don't prevent a class from being considered "trivially copyable". However, they do participate in overload resolution when it comes time to actually copy them, so they can interfere. And since a in this example is a non-const l-value, it better fits the signature A(A&) than it does A(const A&). So it calls the template function.

(Though why you didn't bother to explain all of this in your question eludes me, since you obviously did your research.)

However, considering how small of a corner-case this is, I wouldn't go around relying on this behavior to force trivially copyable classes into not being trivially copied.

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