模板代码是这样的:
template <class type1>
struct DefaultInstanceCreator {
type1 * operator ()() {
return new type1;
}
};
template < class type1
, class InstanceCreator = DefaultInstanceCreator<type1> >
class objectCache
{
public:
objectCache (InstanceCreator & instCreator)
:instCreator_ (instCreator) {}
type1* Get() {
type1 * temp = instCreator_ ();
}
private:
InstanceCreator instCreator_;
};
Run Code Online (Sandbox Code Playgroud)
这段代码适用于像这样的对象类:
class A{
public:
A(int num){
number = num;
}
int number;
struct CreateInstance {
CreateInstance (int value) : value_ (value) {}
A * operator ()() const{
return new A(value_);
}
int value_;
};
};
objectCache< A, A::CreateInstance > intcache(A::CreateInstance(2));
A* temp = intcache.Get();
cout << temp->number <<endl;
Run Code Online (Sandbox Code Playgroud)
当我尝试使用类型为int,string的模板时...
objectCache< int > intcache();
int* temp = intcache.Get();
*temp = 3;
cout <<temp <<endl;
Run Code Online (Sandbox Code Playgroud)
我得到E'左边的''.Get'必须有class/struct/union",我找不到问题出在哪里
当我换到
objectCache< int > intcache;
Run Code Online (Sandbox Code Playgroud)
我得到''objectCache':没有合适的默认构造函数可用"
使用
objectCache< int > intcache(DefaultInstanceCreator<int>());
Run Code Online (Sandbox Code Playgroud)
我离开了''.Get'也必须有class/struct/union".
在这里,您没有将参数传递给intcache构造函数:
objectCache< int > intcache();
int* temp = intcache.Get();
Run Code Online (Sandbox Code Playgroud)
这导致第一行恢复到C++的众所周知的"最令人烦恼的解析",简而言之,您声明intcache为不带参数和返回的函数objectCache<int>.
也许你的意思是:
objectCache< int > intcache;
Run Code Online (Sandbox Code Playgroud)
但可能你想通过工厂:
objectCache< int > intcache((DefaultInstanceCreator<int>()));
Run Code Online (Sandbox Code Playgroud)