更新:编辑以修复工作示例中的编译。
我想做类似于下面的操作,这样函数就可以接受枚举类示例的列表或包含它们的结构体,但是auto myFunc2<EList<Types...>>
的定义失败了,expected a constant not E::A
#include <cstdint>
#include <iostream>
enum class E {A = 0, B=1};
template<E... Types> struct tl2 {};
using my_list_2 = tl2<E::A>;
template <E ... Types>
auto myFunc2 = [] {
std::cout << "Size: " << sizeof...(Types) << std::endl;
};
template <template<E...> typename EList, E... Types>
auto myFunc2<EList<Types...>> = [] {
std::cout << "Size: " << sizeof...(Types) << std::endl;
};
int main() {
myFunc2<E::A, E::B>(); // This call prints size of typelist
//Works when myFunc2<Elist<Types..>> is commented out
//myFunc2<my_list_2>(); //This breaks
}
如果我们将其转换为一般类型,那么一切都可以编译并按预期工作。例如:
#include <cstdint>
#include <iostream>
template < typename ... Types > struct tl
{
};
using my_list = tl <int, float, uint64_t>;
template <typename ... Types>
static constexpr auto myFunc2 = [] {
std::cout << "Size: " << sizeof...(Types) << std::endl;
};
template <template<class...> class TL, typename ... Types>
static constexpr auto myFunc2<TL<Types...>> = [] {
std::cout << "Size: " << sizeof...(Types) << std::endl;
};
int main() {
myFunc2<int,uint64_t,bool,uint16_t>();
myFunc2<my_list>();
}
这是怎么回事?在如何将枚举类作为模板处理方面有限制吗?
1条答案
按热度按时间b5buobof1#
真正的函数模板可以做到这一点(使用通常用于推导包的额外助手):
这种方法允许“一个模板”接受不同类型的模板参数,因为在重载解析期间,具有错误类型的模板参数的模板将被简单地忽略。