'How to know if optional template parameter was not given?
Is is possible to know if an optional template parameter was not given/set? Made an attempt with std::is_empty to no avail.
template<class T, class U = int>
class A {
public:
T x;
U y;
void check() {
if (std::is_empty<U>::value)
std::cout << "not given\n";
else
std::cout << "given\n";
}
};
int main()
{
A<float> a(1.5);
a.check();
}
Solution 1:[1]
If it is not supplied by the user, it is int:
template<class T, class U = int>
^^^^^
that is what = int means.
There is no way to tell within the template if int was passed explicitly or if it was set implicitly by skipping it.
You can make A<float> different from A<float, int> in a number of ways.
You could U = void then set RealU within the template to U unless it is void, and int if it is void.
You could take class...U and restrict your code to sizeof...(U)<=1. Then do the same RealU trick.
You could make a wrapper template that does this stuff, and have the real template get passed T, U and a bool saying if U was passed.
In every case, the type of A<float> will not match the type of A<float, int> because you are implicitly demanding that to be the case.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | cigien |
