lundi 3 avril 2017

C++ variadic template with doubles

The following code

#include <initializer_list>
#include <vector>

template<int ...>
const std::vector<int>*make_from_ints(int args...)
{ return new std::vector<int>(std::initializer_list<int>{args}); }

is compiling (with GCC 6.3, on Debian/Sid/x86-64) correctly, and I expect it for a call like

auto vec = make_from_ints(1,2,3);

to return a pointer to some vector of integers containing 1, 2, 3.

However, if I replace int by double, that is if I add the following (in the same basiletemplates.cc file ...) code:

template<double ...>
const std::vector<double>*make_from_doubles(double args...)
{ return new std::vector<double>(std::initializer_list<double>{args}); }

I'm getting a compile error:

basiletemplates.cc:8:17: error: ‘double’ is not a valid type
                for a template non-type parameter
 template<double ...>
                 ^~~

and I don't understand why. After all both int and double are scalar numerical POD types (predefined in the C++11 standard).

How to get a template variadic function to be able to code:

auto dvec = make_from_doubles(-1.0, 2.0, 4.0);

and get a pointer to some vector of doubles containing -1.0, 2.0, 4.0 ?

BTW, compiling for C++14 (with g++ -Wall -std=c++14 -c basiletemplates.cc), and using clang++ (version 3.8.1) instead of g++ dont change anything.

Aucun commentaire:

Enregistrer un commentaire