c++ - `enum class` 的冗余语法

标签 c++ c++11

假设我有一个模板化类,我在其中使用 enum class作为模板参数。这是一个完整的(简单的)示例:

enum class AnimalType { Dog, Cat, Hamster };

template <AnimalType>
class Animal {
public:
  std::string speak();
};

template <>
std::string Animal<AnimalType::Dog>::speak() {
  return "Woof";
}

template <>
std::string Animal<AnimalType::Cat>::speak() {
  return "Meow";
}

template <>
std::string Animal<AnimalType::Hamster>::speak() {
  return "Iä! Iä! Cthulhu fhtagn!";
}

int main() {
  Animal<AnimalType::Dog> dog;
  Animal<AnimalType::Cat> cat;
  Animal<AnimalType::Hamster> hamster;

  cout << dog.speak() << endl << cat.speak() << endl << hamster.speak() << endl;
}

有没有办法避免冗长和多余的Animal<AnimalType::Hamster>语法?

最佳答案

将类及其enum class放入命名空间中,它们可以有简短的名称:

namespace Animal {

enum class Type { Dog, Cat, Hamster };

template <Type>
class Animal {
public:
  std::string speak();
};

template <>
std::string Animal<Type::Dog>::speak() {
  return "Woof";
}

… etc

} // namespace Animal

然后在更窄的范围内使用 using 语句:

int main(){
  using Animal::Animal;
  using Animal::Type; // error
  Animal<Type::Dog> dog;
  Animal<Type::Cat> cat;
  … etc
}

如果类和命名空间具有相同的名称,则不能编写 using Animal::Type;,因为它有歧义。但是您可以使用全局范围符号来明确表明您正在使用命名空间:

int main(){
  using ::Animal::Animal;
  using ::Animal::Type; // ok
  Animal<Type::Dog> dog; 
  … etc
}

关于c++ - `enum class` 的冗余语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41338386/

相关文章:

c++ - 背景提取

c++ - 评估 cout 是否具有 constexpr 值?

c++11 - 在具有 protected 析构函数的类中使用 unique_ptr

c++ - 为什么将对象引用参数传递给线程函数无法编译?

C++11/C++03 和 std::vector 线程安全

c++ - Qt Creator C1083 : Cannot open include file: 'cstddef' : No such file or directory

c++ - 使用 waitpid 等待另一个进程的线程

c++ - 如何将 C/C++ 库集成到 Objective-C 中

c++ - Opencv:如何计算 3d 直方图?

c++ - `*this` 外部成员函数体?