Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template template parameters without specifying inner type

I want to know if it is at all possible to have code that has the following behaviour:

int main()
{
    func<vector>(/*some arguments*/);
}

That is, I want the user to be able to specify the container without specifying the type that it operates on.

For example, some (meta) code (which does not work with the above) that might define func would be as follows:

template<typename ContainerType>
int func(/*some parameters*/)
{
    ContainerType<int> some_container;
    /*
        operate on some_container here
    */
    return find_value(some_container);
}
like image 290
Konrad Avatar asked Jul 05 '16 10:07

Konrad


People also ask

Can we use non-type parameters as argument templates?

A non-type template argument provided within a template argument list is an expression whose value can be determined at compile time. Such arguments must be constant expressions, addresses of functions or objects with external linkage, or addresses of static class members.

What is a non-type template parameter?

A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument. A non-type parameter can be any of the following types: An integral type. An enumeration type. A pointer or reference to a class object.

Can template have default parameters?

You cannot give default arguments to the same template parameters in different declarations in the same scope. The compiler will not allow the following example: template<class T = char> class X; template<class T = char> class X { };

Which is correct example of template parameters?

For example, given a specialization Stack<int>, “int” is a template argument. Instantiation: This is when the compiler generates a regular class, method, or function by substituting each of the template's parameters with a concrete type.


2 Answers

The syntax is

template <template <typename...> class ContainerType>
int func(/*some parameters*/)
{
    // Your code with ContainerType<int>
}

Note: class cannot be replaced by typename (until c++17).

You cannot simply use typename instead of typename... Because std::vector takes Type and Allocator (defaulted): std::vector<T, Allocator>

like image 124
Jarod42 Avatar answered Oct 24 '22 19:10

Jarod42


Try this:

template<template<typename,typename> class ContainerType>
int func (/*some parameters*/)
{

}

You need two inner template parameters since std::vector is defined as:

template < class T, class Alloc = allocator<T> > class vector;

like image 29
Mattia F. Avatar answered Oct 24 '22 18:10

Mattia F.