Date: Fri, 25 Mar 2022 10:47:07 +0000
Let's say I have a template function as follows:
template<class T>
void Func(T &arg)
{
/* Do Something */
}
And let's say that my function can be used in a program as follows:
#include <iostream>
int main(void)
{
Func(std::cout);
}
However I don't want my function to be used like this. I want the
programmer to have to explicitly specify the type, as follows:
Func<ostream>(std::cout);
In order to impose this restriction, I have to rewrite my template
function as follows:
#include <type_traits>
template <class T>
void Func(typename std::common_type<T>::type &obj)
{
/* Do Something */
}
After having made this change, the following line no longer compiles:
Func(std::cout);
and this is exactly the behaviour I want.
I think we should make use of the "explicit" keyword to disable
argument-based template parameter deduction, as follows:
template<explicit class T>
void Func(T &arg)
{
/* Do Something */
}
template<class T>
void Func(T &arg)
{
/* Do Something */
}
And let's say that my function can be used in a program as follows:
#include <iostream>
int main(void)
{
Func(std::cout);
}
However I don't want my function to be used like this. I want the
programmer to have to explicitly specify the type, as follows:
Func<ostream>(std::cout);
In order to impose this restriction, I have to rewrite my template
function as follows:
#include <type_traits>
template <class T>
void Func(typename std::common_type<T>::type &obj)
{
/* Do Something */
}
After having made this change, the following line no longer compiles:
Func(std::cout);
and this is exactly the behaviour I want.
I think we should make use of the "explicit" keyword to disable
argument-based template parameter deduction, as follows:
template<explicit class T>
void Func(T &arg)
{
/* Do Something */
}
Received on 2022-03-25 10:47:20