Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way for a C++ template function to take exactly N arguments?

Tags:

c++

templates

What I mean is, for example, a constructor for a class like the following:

class vector<size_t N, typename FLOAT=double> {
    vector(FLOAT ...x) {} // I want exactly N arguments here
};

I hope it's clear that I do not want a variadic function, but a function that takes exactly N arguments, when N is known at compile-time. Thus, using the example above, vector<3>(1.5, 2.5) should produce a compile-time error, while vector<2>(1.5, 2.5) should compile and run.

Is this possible?

I was thinking that perhaps this could be done with parameter packs, but I'm not quite sure how.

like image 933
Matt Avatar asked Feb 16 '18 00:02

Matt


People also ask

Can template function take any number of arguments?

Variadic templates are class or function templates, that can take any variable(zero or more) number of arguments. In C++, templates can have a fixed number of parameters only that have to be specified at the time of declaration.

Can there be more than one argument to template?

Function TemplateFunction overloading can take varying numbers of arguments.

Can you have templates with two or more generic arguments?

Function Templates with Multiple ParametersYou can also use multiple parameters in your function template. The above syntax will accept any number of arguments of different types. Above, we used two generic types such as A and B in the template function.


1 Answers

With some indirection, you may do something like:

template <std::size_t, typename T> using alwaysT = T;

template <typename FLOAT, typename Seq> struct vector_impl;

template <typename FLOAT, std::size_t... Is>
struct vector_impl<FLOAT, std::index_sequence<Is...>> {
     vector_impl(alwaysT<Is, FLOAT>... floats) { /*...*/}
};

template <std::size_t N, typename FLOAT>
using vector = vector_impl<FLOAT, std::make_index_sequence<N>>;
like image 190
Jarod42 Avatar answered Oct 02 '22 21:10

Jarod42