geometrian
geometrian

Reputation: 15377

Template Specialized Constructor With n Arguments

I have a class that is templated with ints (i.e.:

template </*...*/, int a> /*...*/

). In my class, I would like a constructor that takes exactly "a" arguments. I can of course make it variadic, but I'd like compile-time checks on length if possible. I also think macro hacks could work, but I'm starting by looking for built-in C++ functionality.

Is this possible in C++, and how can it done if so?

Upvotes: 0

Views: 114

Answers (1)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145204

Dealing with a sequence of values of the same type is what arrays are for.

You don't even need to use raw arrays; with C++11 you can use std::array.

E.g. like so:

template< int a >
class MyClass
{
public:
    MyClass( std::array< int, a > const& args )
    {}
};

If your compiler doesn't offer std::array then you can very easily define a corresponding class, or you can just use a raw array:

template< int a >
class MyClass
{
public:
    MyClass( int const (&args)[a] )
    {}
};

Hm, I hope I got the placement of & correct there. For some reason that I can't fathom, I always forget that syntax. No matter how many times I've used it.


Given that the OP clarifies in a comment that (1) he doesn't have C++11 and (2) he wants simple declaration syntax like

MyClass<4> m(0,1,2,3);

one possibility is to make MyClass an aggregate that can be initialized by C++03 curly braces initializer, i.e., no user defined constructor:

#include <stddef.h>

typedef ptrdiff_t Size;
typedef Size Index;

template< Size a >
class MyClass
{
public:
    static Size const n = a;
    static Size size() { return n; }

    int elems_[n];
    int operator[]( Index const i ) const { return elems_[i]; }
    int& operator[]( Index const i ) { return elems_[i]; }
};

#include <iostream>
using namespace std;
int main()
{
    MyClass< 3 > x = {100, 200, 300};
    for( int i = 0;  i < x.size(); ++i )
    {
        wcout << x[i] << endl;
    }
}

If this solution is acceptable then it's essentially to reimplement std::array.

Upvotes: 2

Related Questions