我正在尝试创建一个模板,该模板将接受对对象的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;
^
我尝试了许多方法,但无法解决编译问题?怎么解决一样?
编辑: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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句