Home > Back-end >  How to specialize a function using enum
How to specialize a function using enum

Time:09-17

I'm trying to refactor some code. Basically is a state machine based with enum. There are a lot of switch statements and functions that got called with different names and ambiguations.

Since they force me to keep the enum, I would like to refactor it using template. Basically I would like to use template to implement polymorphism. Since the states are limited there should be a way but I cannot find the best one.

#include <iostream>

enum class AnimalType
{
    Dog,
    Cat
};

template<AnimalType T>
void Foo()
{
    std::cout << "Unknown animal\n";
}

template<>
void Foo<AnimalType::Dog>()
{
    std::cout << "I'm a dog\n";
}

template<>
void Foo<AnimalType::Cat>()
{
    std::cout << "I'm a cat\n";
}

int main()
{
    AnimalType CurrentAnimal = AnimalType::Dog;
    // Foo<CurrentAnimal>(); Won't compile
    return 0;
}

CodePudding user response:

You need a compile time evaluatable constant, this will work

int main()
{
    constexpr auto CurrentAnimal = AnimalType::Dog;
    Foo<CurrentAnimal>();
    return 0;
}

or directly use

Foo<AnimalType::Dog>();  

Note : you can't use your construct to make decissions at runtime. Templates only lead to compile time polymorphism

CodePudding user response:

As mentioned by enter image description here

  • Related