在处理结构模板中的整数时如何修复"X 不是类模板"?

How to fix 'X is not a class template' when dealing with ints in struct templates?

本文关键字:何修复 结构 处理 整数      更新时间:2023-10-16

我无法编译我的代码,我正在尝试拥有一个类,该类使用接受 int 和参数包的结构模板存储有关类型的信息。

#include <tuple>
#include <cassert>
#include <iostream>
#include <cstring>
#include <vector>
template<int N, typename... Ts>
    struct type_info_impl<N, Ts...> {
    typedef typename std::tuple_element<N, std::tuple<Ts...>>::type type;
    static const size_t size = sizeof(type);
};
template<typename... Types>
class type_info {
    public:
      type_info(){}
      ~type_info(){}
      template<int N>
      static constexpr size_t size(){
        return type_info_impl<N, Types...>::size;
      }
};
using types = type_info<bool, int, double>;
using namespace std;
int main()
{
   cout << types::size<1>() << endl; 
   return 0;
}

应该输出数字"4",因为索引 1 处的类型 (int) 的大小为 4,但它抛出 "'type_info_impl' 不是类模板 结构type_info_impl {"

您用来定义type_info_impl的语法是错误的。

用途

template<int N, typename... Ts>
    struct type_info_impl<N, Ts...> { ...};

如果您尝试专用化类模板,则可以。若要定义基本类模板,请删除<N, Ts...>位。只需使用

template<int N, typename... Ts>
    struct type_info_impl { ...};