如何将对象数组作为参数传递给模板

How to pass array of objects as a parameter to template

本文关键字:参数传递 对象 数组      更新时间:2023-10-16

我正在尝试创建一个模板,该模板将接受对 C 样式对象数组的引用作为参数:

#include <iostream>
class A
{
public:
A(){}
};
template<int N, class A& obj> struct W {};
int main()
{
A b[5]; 
W<5,b> w; 
}

但是在编译代码时出现错误:

$ c++ -std=c++11 -g try37.cpp
try37.cpp: In function 'int main()':
try37.cpp:14:5: error: the value of 'b' is not usable in a constant expression
W<5,b> w;
^
try37.cpp:13:3: note: 'b' was not declared 'constexpr'
A b[5];
^
try37.cpp:14:6: error: could not convert template argument 'b' to 'A&'
W<5,b> w;
^
try37.cpp:14:9: error: invalid type in declaration before ';' token
W<5,b> w;
^

我尝试了很多方法,但无法解决编译问题?如何解决相同问题?

你的代码中存在一些问题。

(1(如果要将对对象的引用作为模板参数传递,则必须将其定义为constexpr并为其提供外部static链接(static不是必需的,请从birdfreeyahoo更正(谢谢!

constexpr A b[5]; 
int main ()
{
W<5,b> w; 
}

(2(如果你想用默认构造函数初始化一个(C风格的数组(constexprA对象,你也必须contexpr构造函数。

所以

public:
constexpr A(){}

(3( 如果您希望W的第二个模板参数是对As 的常量 C 样式数组的引用,其中维度是第一个参数,则语法为

template <int N, A const (& obj)[N]>
struct W
{ };

所以完整的程序变成了

class A
{
public:
constexpr A ()
{ }
};
template <int N, A const (& obj)[N]>
struct W
{ };
constexpr A b[5]; 
int main ()
{
W<5, b> w; 
}

编辑:C 样式数组被添加到答案中。

如果你试图让结构 W 有一个对象的容器,你可以使用向量,但是。我仍然不确定你为什么要这样做。

struct W
{
template<typename Type, typename A> //constructor with a vector
W(std::vector<Type,A> & vec)
{
//...
}
template<typename Type>
W(int arraySize, Type & obj) //constructor with an array
{
//...
}
};
int main()
{
const int ArraySize = 5;
A b[ArraySize];
std::vector<A> vec;
for(int i =0; i < 5; i++)
vec.push_back(b[i]);
W w(vec); //calling struct W constructor that takes a vector.
W w2(ArraySize,b); //calling struct W constructor that takes c style array
return 0;
}

首先,您只能将 A 的 1 个实例传递给模板。 将其更改为A[n] obj注意:它将转换为指向 A!

其次,您传递的数组必须具有静态存储持续时间。因此,要么使数组静态,要么将其作为全局变量。

template < typename TElement, std::size_t NElement>
constexpr std::size_t sizeof_array( TElement const (&arr)[NElement] )
{
(void)arr; // Unused, could have been anonymous
return NElement;
}
template < typename TArray>
constexpr std::size_t sizeof_array2( const TArray& arr )
{
return ( sizeof( arr ) / sizeof( arr[0] ) );
}

然后在您的代码中:

char arr[] = "abcdef;
sizeof_array(arr); // C-styled array
sizeof_array2(arr);