Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/154.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 从数组的类型获取数组的大小_C++_Templates - Fatal编程技术网

C++ 从数组的类型获取数组的大小

C++ 从数组的类型获取数组的大小,c++,templates,C++,Templates,我有一个模板参数T,我知道它将是一个 MyArray<Tbis, n> MyArray 有没有办法返回整数n,以便我可以将其用作模板参数 向您问好,是的。成员函数(至少在Visual Studio 2010上)size()和max\u size()都返回项目数 #include "stdafx.h" #include <array> #include <iostream> template<class T> int tuple_size(T

我有一个模板参数T,我知道它将是一个

MyArray<Tbis, n>
MyArray
有没有办法返回整数n,以便我可以将其用作模板参数

向您问好,

是的。成员函数(至少在Visual Studio 2010上)
size()
max\u size()
都返回项目数

#include "stdafx.h"
#include <array>
#include <iostream>

template<class T>
int tuple_size(T t)
{
    return std::tuple_size<T>::value;
}

int main()
{ 
    std::array<int, 4> nums;
    std::cout << "size(): " << nums.size() << "\n";
    std::cout << "max_size(): " << nums.max_size() << "\n";
    std::cout << "tuple_size: " << tuple_size(nums)  << "\n";
}
#包括“stdafx.h”
#包括
#包括
模板
整数元组大小(T)
{
返回std::tuple_size::value;
}
int main()
{ 
std::数组nums;

这就是你想要做的吗

#include <iostream>
#include <array>

template <typename T, size_t N>
void f(std::array<T, N>& a)
{
    std::cout << N << '\n'; 
}

int main()
{
    std::array<int, 34> a;
    f(a);
}
#包括
#包括
模板
空f(标准::数组和a)
{

如果我正确理解了这个问题,那么您需要获取数组的大小,并将其用作模板参数

大概是这样的:

#include <iostream>
#include <array>


typedef std::array< int, 72 > myArray;

template< int N = myArray().size() >
struct A
{
    void foo()
    {
        std::cout << N << std::endl;
    }
};

int main()
{
    A<> a;

    a.foo();
}
#包括
#包括
typedef std::arraymyArray;
模板
结构A
{
void foo()
{

库特·皮奥特:我已经改变了我的问题。谢谢你的提示。为什么我得到了-1?为什么是-1?
size()
是一个constepr,可以用作模板参数。我也回答了一个未经编辑的问题。如果我在开始VS之前看到了编辑过的版本,并编写了测试来检查我的答案,我也会使用tuple_size。@Bаћ:
size()
是C++11之后的constepr,而不是以前的。非常感谢你的帮助。MyArray有一个size()方法,比如std::array。因此,我已经能够实现您的想法,将大小更改为constexpr。为什么不使用std::array?graham.reeds:我正在构建自己的库。我不想使用std::vector,因为标准库处理改变对象类型的分配器的方式。我还希望代码的可移植性(例如,绑定检查是不可移植的,因为无法在调试模式下以可移植的方式绑定检查[]运算符)。我想构建一些与此处可用内容相近的内容:。为了一致性,我开发了自己的std::array.Sweet.Fight模板和模板;-)。这个想法当然也适用于MyArray。