The compiler gives an error when I try this. I tried with both VC++ and g++.
This applies equally to function templates and class templates (though for function templates the compiler error only occurs if and when the function template is instantiated; the compiler error for class template occurs immediately when the compiler encounters the second class definition).
Here is an example for a function template:
template <unsigned int>
void Foo() {}
template <signed int> // Same name, only difference is the type of the
void Foo() {} // non-type template parameter (of integral type)
Foo<10U>(); // COMPILER ERROR.
Above, why can't the compiler just instantiate Foo<unsigned int>()
?
I found that this is not an issue if the second version of the template function/class has a type template parameter. It also is not an issue if the second version of the template function/class has or a non-type template parameter of non-integral type:
template <unsigned int>
void Foo() {}
template <unsigned int*> // Non-type template parameter
void Foo() {} // of non-integral type
template <typename T> // Type template parameter
void Foo() {}
Foo<10U>(); // OK
So if I had to guess I'd say it has something to do with the fact that the compiler can convert between values of integral types? But that doesn't stop C++ from allowing two overloading functions that differ only by the type of on integral parameter.
Explanation: Just like normal parameters we can pass more than one or more template parameters to a template class.
CLASS TEMPLATE WITH MULTIPLE PARAMETERSWe can use more than one generic data type in a class template, and each generic data type is separated by the comma.
For normal code, you would use a class template when you want to create a class that is parameterised by a type, and a function template when you want to create a function that can operate on many different types.
There are three primary drawbacks to the use of templates. First, many compilers historically have very poor support for templates, so the use of templates can make code somewhat less portable. Second, almost all compilers produce confusing, unhelpful error messages when errors are detected in template code.
It does allow it, you were able to write the two templates just fine. They just become unusable when instantiated. The reason is that there is no "overload resolution" to choose a template. The only requirement imposed on a non-type template argument is as follows:
[temp.arg.nontype]/2
A template-argument for a non-type template-parameter shall be a converted constant expression of the type of the template-parameter.
And 10u
is a converted constant expression of both int
and unsigned int
type. Valid as an argument for either overload.
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