c – 强制编译器选择带有const T&作为参数的复制构造函数

前端之家收集整理的这篇文章主要介绍了c – 强制编译器选择带有const T&作为参数的复制构造函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在写一个类,我有一个模板化的构造函数和复制构造函数.每次我想用非const对象调用复制构造函数时,都会选择模板化构造函数.如何强制编译器选择复制构造函数

这是mcve:

  1. #include <iostream>
  2.  
  3. struct foo
  4. {
  5. foo()
  6. {
  7. std::cout << "def constructor is invoked\n";
  8. }
  9.  
  10. foo(const foo& other)
  11. {
  12. std::cout << "copy constructor is invoked\n";
  13. }
  14.  
  15. template <typename T>
  16. foo(T&& value)
  17. {
  18. std::cout << "templated constructor is invoked\n";
  19. }
  20. };
  21.  
  22. int main()
  23. {
  24. foo first;
  25. foo second(first);
  26. }

删除功能不是我想要的.

解决方法

问题是,首先是可变的,所以对它的引用是foo&它与通用参考文献T&& amp;比const foo&更容易.

据推测,你打算T是任何非foo类吗?

在这种情况下,一小部分enable_if chicanery表达了对编译器的意图,而不必编写一系列虚假的重载.

  1. #include <iostream>
  2.  
  3. struct foo
  4. {
  5. foo()
  6. {
  7. std::cout << "def constructor is invoked\n";
  8. }
  9.  
  10. foo(const foo& other)
  11. {
  12. std::cout << "copy constructor is invoked\n";
  13. }
  14.  
  15. template <typename T,std::enable_if_t<not std::is_base_of<foo,std::decay_t<T>>::value>* = nullptr>
  16. foo(T&& value)
  17. {
  18. std::cout << "templated constructor is invoked\n";
  19. }
  20.  
  21. };
  22.  
  23. int main()
  24. {
  25. foo first;
  26. foo second(first);
  27. foo(6);
  28. }

预期产量:

  1. def constructor is invoked
  2. copy constructor is invoked
  3. templated constructor is invoked

猜你在找的C&C++相关文章