如何将对象数组作为参数传递给模板
How to pass array of objects as a parameter to template
我正在尝试创建一个模板,该模板将接受对 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风格的数组(constexpr
A
对象,你也必须contexpr
构造函数。
所以
public:
constexpr A(){}
(3( 如果您希望W
的第二个模板参数是对A
s 的常量 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);
相关文章:
- 如何在不使用指针的情况下将派生类的对象作为参数传递给基类中的函数?
- 如何将对象数组作为参数传递给模板
- 如何将成员函数作为参数传递并在派生对象上执行方法列表
- 如何将子类作为函数的参数传递给期望基类,然后将该对象传递到指向这些抽象类对象的指针向量中?
- 对象作为参数传递,就好像我们正在传递构造函数值一样
- 初始化对象以在 C++08 中作为参数传递的首选语法是什么?
- 将对象作为参数传递,没有可行的重载"="
- 当我按值传递参数时对象被破坏时?
- 在将匿名对象作为参数传递时,不会调用任何构造函数
- 是否可以创建一个指向对象的智能指针并将此智能指针作为参数传递给构造函数?
- C++:将对象作为参数传递
- 将 std::ofstream 对象作为参数传递给类方法
- 将对象向量的指针作为参数传递,但差异更大
- 当数组对象以函数参数传递时,为什么复制构造函数会自称
- 如何将对象作为参数传递
- 将对象作为C 中的参数传递
- 将新对象的名称作为参数传递
- 将对象数组作为参数传递的最佳方法是什么
- 为什么将临时对象作为参数传递需要 std::move?
- 将任何数据类型/对象作为参数传递以确定其大小