1
votes

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
The template itself shouldn't even compile.. template<T, ALLOC> CONT says that CONT is a template with two non-type template parameters whose types are T and ALLOC. This should cause name lookup of T and ALLOC which should fail. -- Like this: coliru.stacked-crooked.com/a/50c8edf643ed26f0dyp
Oh, and you forgot the class before CONT, if this is supposed to be a template template-parameter: template<template</*something*/> class CONT>dyp

1 Answers

3
votes

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;
}