Specialize only one template class method

Asked

Viewed 66 times

4

I own 2 basic class types, Classea and Classeb. Classea has a method that generates an integer, and Classeb has a method that generates a Classea.

I would like in the method of a Classec, if the template is a Classea(or daughters) returns the integer by the method directly, and if the template is a Classeb(or daughters) generates a Classea and then returns the value by the method, if any other it returns 0.

I summarized the codes to make it easier :

//ClasseA.h
class ClasseA{
public:
    int valor;
    ClasseA(int valor) : valor(valor){
    }
    int retValor() {
        int valor_final = valor;
        //alguns calculos
        return valor_final;
    }
}
//ClasseB.h
class ClasseB{
public:
    int valorA, valorB;
    ClasseB(int valorA, int valorB) : valorA(valorA) , valorB(valorB){
    }
    ClasseA toA() {
        int valor_finalA = valorA;
        int valor_finalB = valorB;
        //alguns calculos
        return ClasseA(valor_finalA / valor_finalB );
    }
}
//ClasseC.h
template<typename T> 
class ClasseC{
public:
    T classeT;
    ClasseC(T classeT) : classeT(classeT) {
    }
    //vários métodos
    int retValorFinal();
}
//ClasseC.cpp
template<typename T> 
int ClasseC<T>::retValorFinal(){
    //????
}
template class ClasseC<ClasseA>;
template class ClasseC<ClasseB>;
//outros tipos

1 answer

2


A possible solution is to make different versions of the method depending on the template class.

template<>
int ClasseC<ClasseA>::retValorFinal() {
    std::cout << "Classe A\n";
    return classeT.retValor();
}

template<>
int ClasseC<ClasseB>::retValorFinal() {
    std::cout << "Classe B\n";
    return classeT.toA().retValor();
}

template<typename T>
int ClasseC<T>::retValorFinal() {
    std::cout << "Classe Desconhecida\n";
    return 0;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.