我有一些自動生成的結構,每個結構都與列舉值邏輯相關。我可以使用模板函式創建工廠嗎?一切都可以在編譯時解決。我試過這樣的事情:
struct Type1
{
};
struct Type2
{
};
enum class type_t
{
first,
second
};
template <type_t typet>
auto Get_()
{
static_assert(typet == type_t::second);
return Type2();
}
template <type_t typet>
auto Get_()
{
static_assert(typet == type_t::first);
return Type1();
}
template <type_t typet>
auto Get_()
{
static_assert(false, "no overload");
}
int main()
{
auto relatedType1 = Get_<type_t::first>();
auto relatedType2 = Get_<type_t::second>();
}
uj5u.com熱心網友回復:
在 C 11(及更高版本)中,您可以使用如下的輔助特征結構:
template <type_t T>
struct type_selector;
template <>
struct type_selector<type_t::first> {
using type = Type1;
};
template <>
struct type_selector<type_t::second> {
using type = Type2;
};
// implement other specializations, if needed
然后,您的Get_函式模板很簡單:
template <type_t typet>
auto Get_() -> typename type_selector<typet>::type {
return {};
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/489105.html
