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)
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)