3

I have the following template class:

template <class T, list<int> t> 
class Tops
{
private:
    list<stack<T>> tops;
public:
    list getTops() {

    }
};

It doesn't compile as: illegal type for non-type template parameter 't',

On line 6: template <class T, list<int> t> class Tops.

When I change the list<int> to type int , it working. what is the problem?

Billie
  • 8,938
  • 12
  • 37
  • 67
  • 1
    Exactly what the error says - `std::list` is not a valid non-type template parameter. See also [here](http://stackoverflow.com/a/5687553/500104). – Xeo Jul 27 '13 at 16:55

2 Answers2

0

Parameter of template is resolved at compile time.

Template arguments must be constant expressions, addresses of functions/objects/static members or references of objects.

I think you're looking for this :

template <class T,list<int> &t> 
class Tops
{
private:
    list<stack<T>> tops;
public:
    list<stack<T> > getTops() {

    }
};
P0W
  • 46,614
  • 9
  • 72
  • 119
0

Change template <class T, list<int> t> to template <class T, list<int> &t>:

template <class T, list<int> &t>   
                             ^^^  //note &t
class Tops
{
private:
    list<stack<T>> tops;
public:
    list getTops() {

    }
};

The reason you can't do this is because non-constant expressions can't be parsed and substituted during compile-time. They could change during runtime, which would require the generation of a new template during runtime, which isn't possible because templates are a compile-time concept.

Here's what the standard allows for non-type template parameters (14.1 [temp.param] p4):

A non-type template-parameter shall have one of the following 
(optionally cv-qualified) types:

 - integral or enumeration type,
 - pointer to object or pointer to function,
 - reference to object or reference to function,,
 - pointer to member.

Source Answer: https://stackoverflow.com/a/5687553/1906361

Community
  • 1
  • 1
Shumail
  • 3,103
  • 4
  • 28
  • 35