Nhu Phuong
Nhu Phuong

Reputation: 427

How to make this template code work?

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.

Upvotes: 0

Views: 371

Answers (3)

1800 INFORMATION
1800 INFORMATION

Reputation: 135463

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>()));

Upvotes: 7

Indy9000
Indy9000

Reputation: 8881

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

objectCache<int> intcache;

Upvotes: 1

Chris Walton
Chris Walton

Reputation: 1346

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

objectCache< int > intcache;

Upvotes: 1

Related Questions