我有以下定义:
enum class Types : unsigned short {T1, T2};
struct Base {};
struct Type1 : Base {};
struct Type2 : Base {};
和返回适当结构的模板函数
template <Types t, typename ...Args>
typename Dispatcher<t>::type*
createInstance(Args...args)
{
return new typename Dispatcher<t>::type(std::forward<Args>(args)...);
}
Dispatcher
在哪里
template <Types> struct Dispatcher {};
template<> struct Dispatcher<Types::T1> { using type = Type1; };
template<> struct Dispatcher<Types::T2> { using type = Type2; };
此auto t1{createInstance<Types::T1>()};
调用可以正常工作。
如果我声明变量const auto a{Types::T1};
然后调用auto t3{createInstance<a>()};
,则该方法有效。
但是我无法在下面的代码循环中完成它:
const std::vector<Types> v{Types::T1, Types::T2, Types::T1};
for (const auto t : v) {
auto tmp {createInstance<t>()};
cout << tmp->name << endl;
delete tmp;
}
选中here。