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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With