我正在尝试创建一个模板,该模板将接受对 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-style array of)constexpr
A
object(s) initialized with default constructor, you have to make contexpr
也是构造函数。
所以
public:
constexpr A(){}
(3) 如果您希望 W
的第二个模板参数是对 A
的常量 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++ - 如何将对象数组作为参数传递给模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52682126/