Nezquick
Nezquick

Reputation: 475

How to use C++ template to have function code based on it

I want to have a class in which one function will depend on the a template that is defined in the instantiation... Like

MyClass<Client1> instance;
instance1.function1();

MyClass<Client2> instance2;
instance2.function1();

then it will use function1 based on that, but I don't want to have to redeclare the whole class for each template, just function1.

How do I declare the class and function?

Upvotes: 0

Views: 59

Answers (3)

Syntactic Fructose
Syntactic Fructose

Reputation: 20076

This sounds like a problem you wouldn't exactly need templates for, you just want a function to act based of a condition passed into the class?

private:
    bool IsStateActive;

//MyClass.cpp

MyClass::MyClass(bool state)
{
    IsStateActive=state;
}

MyClass::function1()
{
    if(state)
        //....
    else
        //.....
}

of course state could also an enum if you would like multiple states as well..

enum { CLIENT1=0, CLIENT2, CLIENT3}
MyClass newObj(CLIENT1); //sets an int to CLIENT0 to be used during function1

why exactly would you like to use templates for this?

Upvotes: 0

jrok
jrok

Reputation: 55395

It's possible to provide an implementation for a single method of a class template. Example:

#include <iostream>

template<typename T>
struct MyClass {
    void function1();
    void common() { std::cout << "common stuff\n"; }
};

class Client1;
class Client2;

template<>
void MyClass<Client1>::function1()
{
    std::cout << "stuff 1\n";
}

template<>
void MyClass<Client2>::function1()
{
    std::cout << "stuff 2\n";
}

int main()
{
    MyClass<Client1> instance1;
    instance1.function1();
    instance1.common();

    MyClass<Client2> instance2;
    instance2.function1();
    instance2.common();
}

Upvotes: 2

camino
camino

Reputation: 10584

you can specialize the function for each instance of the template

Upvotes: -1

Related Questions