我們在使用其中一些成員函數中使用函數對象的類模板時遇到問題。該錯誤消息形成VS2010編譯器:在使用模板時缺少默認構造函數
錯誤C2512: 'SimpleFunctor :: SimpleFunctor':可用
小型化的代碼來重現此如下:沒有適當的默認構造函數 :
// 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() {}
修復了錯誤。
所以問題是,爲什麼編譯器不生成默認的構造函數?
+1對於一個非常好的問題 –