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);
}
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.
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.
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 { };
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.
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>
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With