作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我目前正在使用这个技巧来获得基于类型的 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
>
>
>
>;
}
但是这段代码不是很好看,如果我们想检查更多的类型,这可能是不可读的。是否可以像有一个 switch case block 一样做同样的事情?
实际上,代码比这更复杂,因为 std::conditional 需要一些类型,所以我们需要一些类来解决问题:
struct LicenceName { static char constexpr * value = "licences"; };
例如。
最佳答案
我认为使用模板特化会更容易
示例代码:
#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
}
关于c++ - 想要类型上的 constexpr 开关盒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40746309/
使用登录后,我想吐出用户名。 但是,当我尝试单击登录按钮时, 它给了我力量。 我看着logcat,但是什么也没显示。 这种编码是在说。 它将根据我在登录屏幕中输入的名称来烘烤用户名。 不会有任何密码。
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 这个问题似乎是题外话,因为它缺乏足够的信息来诊断问题。 更详细地描述您的问题或include a min
我是一名优秀的程序员,十分优秀!