枚举值的模板专门化

vch*_*dra 3 c++ templates specialization sfinae

是否可以专门为单个枚举值使用类方法?具体来说,我有一个枚举和一个类,如下所示:

#include <iostream>
#include <stdio.h>

using namespace std;

enum class Animal { dog, cat, bird  };
class Sound
{
   public:
      static void getSound ( const Animal& arg )
      {
         switch ( arg )
         {
           case Animal::dog:
             // dog specific processing
             break;

           case Animal::cat:
             // cat specific processing
             break;

           case Animal::bird:
             // bird specific processing
             break;

           default:
             return;
         }
      }
};
Run Code Online (Sandbox Code Playgroud)

我想专门针对每个枚举值的getSound函数,以摆脱开关的情况。这样的模板专业化可能吗?

S.M*_*.M. 6

对的,这是可能的。查看下面的示例。

#include <iostream>
#include <stdio.h>

using namespace std;

enum class Animal { dog, cat, bird  };
class Sound
{
   public:
      template<Animal animal>
      static void getSound ();
};

template<>
void Sound::getSound<Animal::dog> ()
{
    // dog specific processing
}

template<>
void Sound::getSound<Animal::cat> ()
{
    // cat specific processing
}

template<>
void Sound::getSound<Animal::bird> ()
{
    // bird specific processing
}

int main()
{
    Sound::getSound<Animal::dog>();
}
Run Code Online (Sandbox Code Playgroud)


Sto*_*ica 5

我不明白你为什么想要专业化。如果这个例子是指示性的,并且你的枚举器是顺序的并且从 0 开始,你可以只使用查找表:

enum class Animal { dog, cat, bird, count = (bird - dog + 1) };

static std::string getSound ( Animal arg ) // Pass an enumeration by value, it's cheaper
{
  std::array<char const *, static_cast<std::size_t>(Animal::count)> const sound {{
    "bark", "meow", "chirp"
  }};
  return sound.at(static_cast<std::size_t>(arg));
}
Run Code Online (Sandbox Code Playgroud)

就是这样。它还"unknown"通过抛出的异常替换字符串。我觉得这是有道理的,因为范围枚举意味着我们期望对传递的值进行严格检查。打破这种情况一种特殊情况。


即使您编辑过的问题也可能会受到查找表的影响:

static void getSound ( Animal arg ) // Pass an enumeration by value, it's cheaper
{
  std::array<std::function<void(void)>,
            static_cast<std::size_t>(Animal::count)> const handler{{
    [] { /*Process for dog*/ },
    [] { /*Process for cat*/ },
    [] { /*Process for bird*/ }
  }};
  handler.at(static_cast<std::size_t>(arg))(); // The last () is invocation
}
Run Code Online (Sandbox Code Playgroud)