使用模板时缺少默认构造函数

Hol*_*mar 1 c++ templates

我们在使用类模板时遇到了问题,类模板本身在其某些成员函数中使用了函数对象.VS2010编译器的错误消息是:

错误C2512:'SimpleFunctor :: SimpleFunctor':没有合适的默认构造函数可用

重现的缩小代码如下:

// myfunctor.h

class SimpleFunctor
{
  private:
    SimpleFunctor( const SimpleFunctor& );
    SimpleFunctor& operator=( const SimpleFunctor& );
  public:
    bool operator()() { return true; }
}; 
Run Code Online (Sandbox Code Playgroud)

// 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()();
    }
};
Run Code Online (Sandbox Code Playgroud)

// main.cpp

#include "HK_Template.h"

int main()
{
  Test< int > obj;
  obj.testFunction( 5 );

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

这个例子产生上面的错误信息似乎是正确的,因为将默认构造函数添加到类SimpleFunctor,如:

SimpleFunctor() {}
Run Code Online (Sandbox Code Playgroud)

修复错误.

所以问题是,为什么编译器不生成默认构造函数?

Ker*_* SB 6

一旦您自己定义了任何构造函数(包括复制构造函数),编译器就不再生成默认构造函数.

(另一方面,如果您不提供复制/移动构造函数,则会根据某些规则生成复制/移动构造函数.)