tags:

views:

138

answers:

3

the template code is like this:

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_;
};

this code work well with object class like this:

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;

when I tried this template with type like int, string...

objectCache< int > intcache();
int* temp = intcache.Get();
*temp = 3;
cout <<temp <<endl;

I get E left of "'.Get' must have class/struct/union", I can't find out where is the problem

when I change to

objectCache< int > intcache;

I get "'objectCache' : no appropriate default constructor available"

use

objectCache< int > intcache(DefaultInstanceCreator<int>());

I get left of "'.Get' must have class/struct/union" too.

+1  A: 

You're declaring a function, instead of a variable. Try this:

objectCache< int > intcache;
arke
+7  A: 

In here, you aren't passing in the parameter to the intcache constructor:

objectCache< int > intcache();
int* temp = intcache.Get();

This causes the first line to revert to the well known "most vexing parse" of C++, in short, you are declaring intcache as a function which takes no parameters and returns objectCache<int>.

Maybe you mean this:

objectCache< int > intcache;

But probably you wanted to pass a factory:

objectCache< int > intcache((DefaultInstanceCreator<int>()));
1800 INFORMATION
In the last line, you forgot parentheses around the constructor argument. I fixed that (weird - the questioner had this line in his question too, and wondered about the resulting error - why didn't he ask you?). I would like to mention too that the constructor of `objectCache` would needed to be changed not to accept by non-const reference, so it can accept the temporary.
Johannes Schaub - litb
+1  A: 

Creating an object of objectCache seems wrong. It should be:

objectCache<int> intcache;
Indeera