Nested template parameters and type deduction

1.1k views Asked by At

Hi I am practicing with templates and type deduction and wanted to try making a simple function template with nested template parameters to print out the contents of any stl container:

template <template<T, ALLOC> CONT> 
void Print(const CONT<T, ALLOC> &c) {

    for (const T &elem : c) std::cout << elem << " ";
    std::cout << std::endl;
}

And my test case:

int main() {
    std::list<int> intlist{ 1, 2, 3, 4, 5 };
    std::vector<float> floatvec{ 0.2f, 0.5f };

    Print(intlist);
    Print(floatvec);
}

However I am getting a compiler error whereby the types for T and ALLOC cannot be deduced. Is there a way for me to write this function without having to explicit state the types for the template arguments?

Note that my object here is to be able to deduce the type stored within the passed in stl container. Hence if a vector of ints was passed in T would be deduced to type Int.

1

There are 1 answers

3
Jarod42 On BEST ANSWER

In your case, you may simply do

template <typename CONT> 
void Print(const CONT& c) {
    for (const auto& elem : c) std::cout << elem << " ";
    std::cout << std::endl;
}

If you want to restrict your Print function to template classes with 2 template arguments, the syntax would be:

template <template<typename , typename> class CONT, typename T, typename ALLOC> 
void Print(const CONT<T, ALLOC> &c) {
    for (const T &elem : c) std::cout << elem << " ";
    std::cout << std::endl;
}