想要类型的constexpr开关案例

Fre*_*ios 16 c++ templates metaprogramming

我目前正在做这个技巧,以获得基于类型的cstring:

template<class ListT> static char constexpr * GetNameOfList(void)
{
  return
  std::conditional<
    std::is_same<ListT, LicencesList>::value, "licences",
    std::conditional<
      std::is_same<ListT, BundlesList>::value, "bundles",
      std::conditional<
        std::is_same<ListT, ProductsList>::value, "products",
        std::conditional<
          std::is_same<ListT, UsersList>::value, "users",
          nullptr
        >
      >
    >
  >;
}
Run Code Online (Sandbox Code Playgroud)

但是这段代码不是很好看,如果我们想检查更多类型,这可能是不可读的.这是一种做同样的事情的方式,就像有一个开关盒块?

实际上,代码比这更复杂,因为std :: conditional需要一些类型,所以我们需要一些类来做这个技巧:

struct LicenceName { static char constexpr * value = "licences"; };
Run Code Online (Sandbox Code Playgroud)

例如.

app*_*ple 21

我认为使用模板专业化会更容易


示例代码:

#include <iostream>
struct A{};
struct B{};
struct C{};
struct D{};

template<typename T> constexpr const char* GetNameOfList();
//here you may want to make it return nullptr by default

template<>constexpr const char* GetNameOfList<A>(){return "A";}
template<>constexpr const char* GetNameOfList<B>(){return "B";}
template<>constexpr const char* GetNameOfList<C>(){return "C";}

int main(){
   std::cout << GetNameOfList<A>() << '\n';
   std::cout << GetNameOfList<B>() << '\n';
   std::cout << GetNameOfList<C>() << '\n';
   //std::cout << GetNameOfList<D>() << '\n'; //compile error here
}
Run Code Online (Sandbox Code Playgroud)

  • 不仅更容易,而且更好,因为无效的参数最终会产生编译器错误而不是nullptr,或者至少很容易让它这样做 (2认同)

Que*_*tin 13

你不需要求助于元编程,普通if的工作就好了:

template<class ListT>
constexpr char const *GetNameOfList() {

    if(std::is_same<ListT, A>::value) return "A";
    if(std::is_same<ListT, B>::value) return "B";
    if(std::is_same<ListT, C>::value) return "C";
    if(std::is_same<ListT, D>::value) return "D";

    return nullptr;
}
Run Code Online (Sandbox Code Playgroud)

在Coliru上看到它

  • @hvd:好的,但是你基本上回到了原版的嵌套混乱. (9认同)
  • @Boiethios你有我的同情.我在这里坚持使用VC++ 2008;) (5认同)
  • 通过使用`?:`运算符,可以将这个答案简单地重写为单个`return`语句. (3认同)
  • @hvd:那是嵌套的 (2认同)