Hi :)

I have a problem. I have a class, called Sequence, which is a template. One of it's member variables is a vector or elements of type T. I would like to create a constructor which takes as it's argument an array of elements of type T and feeds them into the vector, but I'm unsure of how to do this. I have tried many attempts but all seem to fail. Here is a snippet of the .h file

template<class T>
class Sequence
{
	public:
		Sequence(){}
                Sequence(T[]); //constructor taking an array of elems of type T
		~Sequence();
	protected:
		std::vector<T> terms;
};

Now including this in a simple driver file doesn't give any syntax errors, however as soon as I try to implement the Sequence(T[]) constructor my compiler starts moaning. I don't have huge experience with templates so maybe I'm missing something obvious, but any pointers (no pun intended) would be much appreciated

Cheers,

Stonehambey

I think his answers your question...although i'm not entirerly sure :D

#include <iostream>
#include <vector>

using namespace std;

template <class T>
class test{
    public:
        test(T[]);
        void print();
    private:
        vector<T> v;
};

int main(void){
    char myArray[] = {'a', 'b', 'f'};

    test<char> myClass(myArray);
    myClass.print();

    cin.get();
    return 0;
}

template <class T>
test<T>::test(T example[]){
    for(int i = 0; i < (sizeof(example)/sizeof(*example))-1; i++){
        v.push_back(example[i]);
    }
}

template <class T>
void test<T>::print(){
    for(int i = 0; i < v.size(); i++){
        cout << "example " << i << ": " << v[i] << endl;
    }
}

Since you never posted what the problematic code was nor the error's you were getting.

Chris

Alas, it's wrong solution because sizeof(T[])/sizeof(T) does not bear a relation to an array size: it's the same as sizeof(T*)/sizeof(T) . Remember: it's impossible to get an array size from type name[] declaration.
Look at:

template <typename T>
class Sequence
{
public:
    Sequence() {}
    Sequence(const T a[], size_t n): terms(a,a+n)
    {} // Use one of std::vector constructors
    void print() const { // illustrative
        for (size_t i = 0; i < terms.size(); ++i)
            std::cout << terms[i] << '\n';
        std::cout.flush();
    }
    //~Sequence(); // No need for the present.
protected:
    std::vector<T> terms;
};

int main()
{
    int arr[] = { 1, 2, 3 };
    Sequence<int> is(arr,sizeof arr/sizeof(arr[0]));
    is.print();
    std::string s[] = { "s1", "s2", "s3" };
    Sequence<std::string> ss(s,sizeof s/sizeof *s);
    ss.print();
    return 0;
}
template <class T>
test<T>::test(T example[]){
//...

This is the syntax I was looking for, thank you :)

I'm not sure about determining an array size, but I'll look into it and post a new thread if I have any problems (as it would be off-topic here)

Thanks again

This question has already been answered. Start a new discussion instead.