Kevin JJ
Kevin JJ

Reputation: 353

c++ template use without argument

There i s template class

template <class T>
class Dao { ... }

and a couple of classes inherit from it. (BarDao and FooDao)

Then, there is another class called Server that must use either BarDao or FooDao figured out dynamically.

So,

class Server {
    Dao * dao;
    Server(Dao * dao) {this->dao = dao;}
}

I get a compilation error complaining about no arguments. How could I avoid getting this error?


Addition.

The reason why I used the template was to accomplish the following:

  1. I wanted to have an abstract class that has methods

    T compute();

  2. BarDao has a method

    SomeClass compute();

  3. FooDao has a method

    SomeOtherClass compute();

Is there better approach than using a template?

Sorry, if questions are dumb. I'm a c++ beginner.

Upvotes: 1

Views: 1271

Answers (2)

amanuel2
amanuel2

Reputation: 4646

Dao in this case is a template not a class. You might want to change your code in the example you gave us Dao :

Dao<int> dao;

Also another idea to point out. You can't have a pointer to a template, but you can to a class. If you are desperate to use a pointer you might as well use a class. Hope this helped!

An alternative to this can be making a string like "int" and based on that you can make if/else method on which method to call. For one method you will have different return values (polymorphism) . Sorry I would give you a code sample but I am answering you via a phone. Here is a good article about polymorphism. Polymorphism is the ugly workaround I can think of now for templates. I might update answer later. Hope this helped!

Upvotes: 1

kfsone
kfsone

Reputation: 24249

Dao is not a concrete class, it is a class template. Dao* dao doesn't refer to an incomplete type, it refers to a template. It needs to be qualified.

You state that you want it resolve automatically, so we just repeat what you're doing in Dao itself.

template<class T>
class Dao
{
    T t_;
public:
    Dao(T t) : t_(t) {}
};

template<class T>
class Server
{
    using dao_t = Dao<T>;

    dao_t* dao_;
public:
    Server(dao_t* dao) : dao_(dao) {}
};

int main() {
    Server<int> server(nullptr);

    return 0;
}

Demo: http://ideone.com/GNcjMm

Upvotes: 2

Related Questions