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

标签 c++ arrays c++11 templates

我正在尝试创建一个模板,该模板将接受对 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/

相关文章:

c++ - 使用牛顿法解决数值问题

c++ - 如何在 operator[] 的声明中将 decltype 应用于成员函数

c++ - 非原子对象在所有线程中是否具有相同的修改顺序? (在没有数据竞争的情况下)

java - java中的拼字游戏数组

c++ - 使用 std::chrono::high_resolution_clock 每秒写入帧 30 次

C++ - 查找倍数并消除常见的

c++ - 从 float C++ 中删除与 int32_t 转换相关的警告消息

c++ - 是 ? : expression not always evaluated?

arrays - 如何在使用速记形式定义的数组中使用完全指定的类型?

php - fatal error : Cannot use string offset as an array?