我有这样的代码: Link to Wandbox
当我尝试编译它时,我得到了这个:
./type_holder.h:45:14: error: no matching constructor for initialization of 'test_class'
return new T(args...);
^ ~~~~
./type_holder.h:54:35: note: in instantiation of member function 'di::DiConstructor<true, test_class, di::DiMark &&, di::AnyResolver>::construct' requested
here
decltype(AnyResolver())>::construct(std::move(DiMark{}), AnyResolver{});
^
test.cc:26:19: note: in instantiation of function template specialization 'di::ConstructIfPossible<test_class>' requested here
std::cout << di::ConstructIfPossible<test_class>() << std::endl;
^
test.cc:14:9: note: candidate constructor not viable: no known conversion from 'di::DiMark' to 'di::DiMark &&' for 1st argument
INJECT(test_class, int* a) {}
^
./inject_markers.h:6:36: note: expanded from macro 'INJECT'
#define INJECT(name, ...) explicit name(di::DiMark&& m, __VA_ARGS__)
^
test.cc:12:7: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 2 were provided
class test_class {
^
test.cc:12:7: note: candidate constructor (the implicit move constructor) not viable: requires 1 argument, but 2 were provided
1 error generated.
问题是我做错了什么?为什么编译器告诉我,我试图将DiMark
转换为DiMark&&
?自从DiMark&&
明确将左值转换为右值后,它是否应该std::move(DiMark) {}
?
答案 0 :(得分:0)
错误告诉你的是你正在尝试使用双参数构造函数构造test_class
对象,但是你没有定义任何对象。
有两个构造函数,都是隐式定义的,它们带有一个参数(复制构造函数和移动构造函数)。但是,由于您尝试使用test_class
和DiMark
参数构造AnyResolver
对象,并且此构造函数不存在,您将收到错误。
要解决此问题,您需要创建一个两参数构造函数。 (然后您可能需要定义副本并移动构造函数,因为如果定义任何其他构造函数,则不会定义隐式构造函数。)