繁体   English   中英

类模板中std :: array的大小取决于模板参数

[英]Size of std::array in class template depending on template parameter

我有以下类模板

template<int N>
constexpr int arraySize() { return arraySize<N-1>() + N; }

template<>
constexpr int arraySize<0>() { return 0; }

template<int C>
class MyClass {
    public:
    std::array<int, arraySize<C>()> arr;
};

int main() {

    MyClass<3> cls;
    std::cout << cls.arr.size() << std::endl;    // Output: 6
}

一切正常但我想将calculateArraySize<N>()作为成员函数。 我尝试过以下方法:

template<int C>
class MyClass {
    public:

    static constexpr int arraySize();
    std::array<int, MyClass<C>::arraySize()> arr;
};

template<int C>
constexpr int MyClass<C>::arraySize(){ return MyClass<C-1>::arraySize() + C; }

template<>
constexpr int MyClass<0>::arraySize() { return 0; }

导致以下错误:

致命错误:递归模板实例化超过最大深度1024 std :: array :: arraySize()> arr;

template<int C>
class MyClass {
    public:

    template<int N>
    static constexpr int arraySize();
    std::array<int, MyClass::arraySize<C>()> arr;
};

template<int C>
template<int N>
constexpr int MyClass<C>::arraySize(){ return MyClass::arraySize<N-1>() + N-1; }

template<int C>
template<>
constexpr int MyClass<C>::arraySize<0>() { return 0; }

给出以下错误:

tmp.cc:19:27:错误:无法专门化(使用'template <>')非特定模板的成员constexpr int MyClass :: arraySize <0>(){return 0; }

是否有可能实现理想的行为? 使用C ++ 14 / C ++ 17功能的解决方案(我想应该可能是usin if-constexpr)受到欢迎但不会解决我的特定问题,因为只有C ++ 11可用。

您可以将该函数移动到类中,并为基本案例专门化整个类。 看起来像:

template<int C>
class MyClass {
    public:

    static constexpr int arraySize(){ return MyClass<C-1>::arraySize() + C; }
    std::array<int, MyClass<C>::arraySize()> arr;
};

template<>
class MyClass<0> {
    public:
    static constexpr int arraySize(){ return 0; }
};

int main() {
    MyClass<3> cls;
    std::cout << cls.arr.size() << std::endl;    // Output: 6
}

实例

您还可以使用成员变量而不是成员函数。

template <int C>
class MyClass {
   public:

      static constexpr int array_size = MyClass<C-1>::array_size + C;
      std::array<int, array_size> arr;
};

template <>
class MyClass<0> {
   public:
       static constexpr int array_size = 0;
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM