문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top