簡體   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