Specialize only one class template method

4

I have 2 basic types of classes, ClasseA and ClasseB . ClassA has a method that generates an integer, and ClassB has a method that generates a ClassA.

I would like the method of a ClassC , if the template is a ClassA (or daughters) return the integer by the method directly, and if the template is a ClassB (or daughters) generate a ClassA and then return the value by the method, if it was any other it would return 0.

I have summarized the codes to facilitate:

//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
    
asked by anonymous 07.11.2016 / 14:05

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;
}
    
07.11.2016 / 16:26