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

标签 c++ templates

我们在使用类模板时遇到问题,该模板本身在其某些成员函数中使用了函数对象。 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/

相关文章:

Eclipse: "Simple"${word_selection} 的模板问题

c++ - 模板模板的 hana 类型

c++ - 从 C# 调用 C++ 函数

c++ - 如何共享 OpenGL 上下文或数据?

c++ - 支持具有固定数组的对象的 BOOST_FUSION_ADAPT_STRUCT?

c++ - 具有动态功能集的 Qt 应用程序

c++ - Visual Studio 2013 中的 "unresolved external symbol"错误

c++ - 非类型模板参数可以实现哪些优化?

templates - GitHub 拉取请求模板 : get current branch name

c++ - 仅为基本数据类型制作模板