我正在写一个类,我有一个模板化的构造函数和复制构造函数.每次我想用非const对象调用复制构造函数时,都会选择模板化构造函数.如何强制编译器选择复制构造函数?
这是mcve:
- #include <iostream>
- struct foo
- {
- foo()
- {
- std::cout << "def constructor is invoked\n";
- }
- foo(const foo& other)
- {
- std::cout << "copy constructor is invoked\n";
- }
- template <typename T>
- foo(T&& value)
- {
- std::cout << "templated constructor is invoked\n";
- }
- };
- int main()
- {
- foo first;
- foo second(first);
- }
解决方法
问题是,首先是可变的,所以对它的引用是foo&它与通用参考文献T&& amp;比const foo&更容易.
据推测,你打算T是任何非foo类吗?
在这种情况下,一小部分enable_if chicanery表达了对编译器的意图,而不必编写一系列虚假的重载.
- #include <iostream>
- struct foo
- {
- foo()
- {
- std::cout << "def constructor is invoked\n";
- }
- foo(const foo& other)
- {
- std::cout << "copy constructor is invoked\n";
- }
- template <typename T,std::enable_if_t<not std::is_base_of<foo,std::decay_t<T>>::value>* = nullptr>
- foo(T&& value)
- {
- std::cout << "templated constructor is invoked\n";
- }
- };
- int main()
- {
- foo first;
- foo second(first);
- foo(6);
- }
预期产量:
- def constructor is invoked
- copy constructor is invoked
- templated constructor is invoked