I want to pass an array into an instance of a class to be used within it.
Ok, there are several ways to do that, I'll show you some of those later.
However, I can't get sizeof()
the array.
You can't get it inside the function, after the array decayed to a pointer.
Store(float temp[]){
// ^^^^^^ This is a pointer to float, not an array
}
Other than explicitly passing the size as a function argument, you could pass a reference to an array, using a template parameter to store the size (1).
#include <vector>
#include <iostream>
class Store
{
std::vector<float> values_;
public:
template< std::size_t N >
Store(float const (&temp)[N]) : values_{temp, temp + N}
{}// ^^^^^^^^^^
void showArrayContents() const noexcept
{
for(auto i : values_)
{
std::cout << ' ' << i;
}
std::cout << '\n';
}
};
int main()
{
float info[]={1.0f,2.3f,1.0f,1.0f,1.0f,1.0f,1.0f,1.0f,1.0f,67.8f};
Store test(info);
test.showArrayContents();
}
Get rid of the source array and use a std::initializer_list
(2).
#include <vector>
#include <iostream>
#include <initializer_list>
class Store
{
std::vector<float> values_;
public:
Store(std::initializer_list<float> src) : values_{src}
{}
//...
};
int main()
{
Store test{1.0f,2.3f,1.0f,1.0f,1.0f,1.0f,1.0f,1.0f,1.0f,67.8f};
test.showArrayContents();
}
If the size never has to change during the lifetime of Store
, you can use a std::array
(3).
#include <algorithm>
#include <array>
#include <iostream>
template< class T, std::size_t N >
class Store
{
std::array<T, N> values_;
public:
Store(T const (&src)[N])
{
std::copy(src, src + N, values_.begin());
}
//...
};
//deduction guide
template<class T, std::size_t N> Store( T (&src)[N] ) -> Store<T, N>;
int main()
{
float info[]={1.0f,2.3f,1.0f,1.0f,1.0f,1.0f,1.0f,1.0f,1.0f,67.8f};
Store test(info);
test.showArrayContents();
}
You can also avoid the source array and initialize the class with a constructor accepting a template parameter pack (4).
#include <algorithm>
#include <array>
#include <iostream>
#include <type_traits>
template< class T, std::size_t N >
class Store
{
std::array<T, N> values_;
public:
template< class... Args >
Store(Args... args) : values_{args...}
{}
//...
};
//deduction guide
template< class... Args >
Store(Args &&... ) -> Store<std::common_type_t<Args...>, sizeof...(Args)>;
int main()
{
Store test{1.0f,2.3f,1.0f,1.0f,1.0f,1.0f,1.0f,1.0f,1.0f,67.8f};
test.showArrayContents();
}