Search code examples
c++templatesc++11initializer-list

Passing std::initializer_list as a non-type template argument


I have a problem with the following code:

#include <deque>
#include <initializer_list>
#include <string>

struct EnumItem
{
    inline operator int() const {
        return id;
    }

    std::string name;
    int id;
};

template <const std::initializer_list<EnumItem>& items>
class Enum
{
public:


private:
    static const std::deque<EnumItem> _items;
};

template <const std::initializer_list<EnumItem>& items>
const std::deque<EnumItem> Enum<items>::_items{ items };

int main() 
{
   Enum<{{"0", 0}}> test;
   return 0;
}

It doesn't compile, throws numerous syntax errors about my test instantiation:

2>error C2059: syntax error : '{'    
2>error C2143: syntax error : missing ';' before '{'     
2>error C2143: syntax error : missing '>' before ';'     
2>error C2976: 'Enum' : too few template arguments     
2>: see declaration of 'Enum'       
2>error C2447: '{' : missing function header (old-style formal list?)      
2>error C2059: syntax error : '>'    

What am I doing wrong and how to do it right?


Solution

  • initializer_list is not a type which can be used with non-type template parameters. In C++14, these are restricted to enums, integers, pointers of all kinds, lvalue references, and nullptr_t.