samedi 6 octobre 2018

How to pass array of objects as a parameter to template

I am trying to create a template that will accept an array of objects as an argument:

#include <iostream>

class A
{
public:
A(){}
};

template<int N, class A& obj> struct W {};

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

But when compile the code I get error:

$ 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;
         ^

I tried many ways but was unable to fix the compilation issue? How to resolve the same?

Aucun commentaire:

Enregistrer un commentaire