mardi 3 mai 2022

C++ function specialization from class template

I have a class, classB which has several functions which I would like to specialize based on an enumerator template S.

I have the following example:

#include <iostream>
#include <string>
#include <array>


typedef std::array<double, 3> vec;
enum Op {Op1, Op2, Op3};

template<class T, enum Op S=Op1>
class classA
{
    public:

    class innerClassA
    {
        public:
   
        void foo() const
        {
            std::cout <<"Operation 1" << std::endl;
        }
    };
};

template<class T>
class classB
{
    public:

    template <Op S = Op1> 
    void myFunc() 
    {
        typename classA<T, S>::template innerClassA myInnerClassObj; 

        for (int i = 0; i < 10; i++)    
            myInnerClassObj.foo();
    }

    // Other functions the I would like to able to speciallize afterwards based on template S
    void myFunc2()  { std::cout << "Func 2" << std::endl; } 
    void myFunc3()  { std::cout << "Func 3" << std::endl; }
};

template<>
void classA<vec, Op2>::innerClassA::foo() const
{
    std::cout << "Operation 2" << std::endl;
}

template<>
void classA<vec, Op3>::innerClassA::foo() const
{
    std::cout << "Operation 3" << std::endl;
}

int main(int argc, char** argv)
{
    classB<vec> obj;
    obj.myFunc();
    obj.myFunc2();
    obj.myFunc<Op2>();
    obj.myFunc<Op3>();

   return 0;
}

In the above example. The function myFunc has a template parameter based on the enumerator. In the main function, I can call the specialized version based on the value of the enumerator. I would also like to do the same for the other functions,myFunc2 however, always having to put:

template <Op S = Op1> 
someFunction()

is quite bothersome. Is there any other way to specify that all functions in a class have a default template based on the enumerator?

Kind regards

Aucun commentaire:

Enregistrer un commentaire