我们在使用类模板时遇到问题,该模板本身在其某些成员函数中使用了函数对象。 VS2010 编译器的错误消息是:
error C2512: 'SimpleFunctor::SimpleFunctor' : no appropriate default constructor available
重现此问题的精简代码如下:
//myfunctor.h
class SimpleFunctor
{
private:
SimpleFunctor( const SimpleFunctor& );
SimpleFunctor& operator=( const SimpleFunctor& );
public:
bool operator()() { return true; }
};
//mytemplate.h
#include "myfunctor.h"
template< typename T >
class Test
{
private:
Test( const Test& );
Test& operator=( const Test& );
public:
Test(){}
void testFunction( T parameter )
{
bool result = SimpleFunctor()();
}
};
// main.cpp
#include "HK_Template.h"
int main()
{
Test< int > obj;
obj.testFunction( 5 );
return 0;
}
这个例子产生了上面的错误消息,这似乎是正确的,因为将默认构造函数添加到类 SimpleFunctor 中,例如:
SimpleFunctor() {}
修复错误。
那么问题来了,为什么编译器不生成默认构造函数呢?
最佳答案
一旦您自己定义了任何构造函数,包括复制构造函数,编译器就不会再生成默认构造函数。
(另一方面,如果您不提供复制/移动构造函数,则默认生成一个复制/移动构造函数,但要遵守某些规则。)
关于c++ - 使用模板时缺少默认构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7930168/