Is this a legitimate method for making sure implicit type conversion does not happen?
#include <string>
#include <iostream>
void func(std::string s)
{
std::cout << "Thanks for the string\n";
}
template<class T>
void func(T)=delete;
int main()
{
func("test1");
// str.cc: In function ‘int main()’:
// str.cc:13:16: error: use of deleted function ‘void func(T) [with T = const char*]’
// func("test1");
// ^
// str.cc:9:6: error: declared here
// void func(T)=delete;
// ^
//
func(std::string("test2"));
return 0;
}
Looks good to me.
It does the same thing to answers.
Yes, that method ensures that implicit conversions are disallowed. However, it also means that this property does not arise from the definition of of void func(string)
alone. So, in order to clarify this to readers, you could make it more self-contained as follows:
template <typename T, typename U> using RequireExplicit = enable_if_t<is_same<T, U>>;
template <typename T, typename = RequireExplicit<T, string>>
void func(T){}
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