AFAIK a template class or function can take default template arguments so I have this example for practice sake I am simulating an adapter class Array
:
template<typename T = int, unsigned sz = 5>
class Array
{
public:
Array(T const& = T());
void push_back(T const&);
void pop_back();
T& front();
T& back();
typename std::vector<T>::iterator begin();
typename std::vector<T>::iterator end();
private:
//std::vector<T> arr_(sz, T()){}; // error: sz is not a type
std::vector<T> arr_{sz, T()};
};
template <typename T, unsigned sz>
Array<T, sz>::Array(T const& val) :
arr_(sz, val)
{}
template <typename T, unsigned sz>
void Array<T, sz>::push_back(T const& x)
{
arr_.push_back(x);
}
template <typename T, unsigned sz>
void Array<T, sz>::pop_back()
{
arr_.pop_back();
}
template <typename T, unsigned sz>
T& Array<T, sz>::front()
{
return arr_.at(0);
}
template <typename T, unsigned sz>
T& Array<T, sz>::back()
{
return arr_.at(sz - 1);
}
template <typename T, unsigned sz>
typename std::vector<T>::iterator Array<T, sz>::begin()
{
return arr_.begin();
}
template <typename T, unsigned sz>
typename std::vector<T>::iterator Array<T, sz>::end()
{
return arr_.end();
}
int main()
{
Array<> ar_d(3.14);
for(auto const& e : ar_d)
std::cout << e << ", ";
std::cout << '\n';
//Array<char*> ar("Hi there!");// works
//Array<char*, 10> ar("Hi there!"); // works
Array<> ar("Hi there!"); // why this doesn't work? : invalid conversion from const char* to int
std::cout << "\ndone!\n";
}
Why I can't declare the member
arr_
that whystd::vector<T> arr_(sz, T()){};
but usingstd::vector<T> arr_{sz, T()};
works? is the first wrong because of some vexing-parse errors?As you can see I class template
Array
has defaults for all of its template arguments and a default value for the constructor so why I can't write this:Array<> ar("Hi there!");
?
Because as I guess arr_
is initialized from the default value of sz_
which is 5
and the constructor deduces the type of "Hi there!" as const char*
so in other words arr_
is a vector of 5 const char* ("Hi there!", "Hi there!"...) But I get the error: cannot convert from const char* to int
.
The error:
In function ‘int main()’: invalid conversion from ‘const char*’ to ‘int’ [-fpermissive]| note: initializing argument 1 of ‘Array<T, sz>::Array(const T&) [with T = int; unsigned int sz = 5]’
In the remaining initializations in main are correct.
Thank you!