Is this a legal method to ensure implicit type conversion does not occur

Is this a legitimate method to ensure that implicit type conversion does not occur?

#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;
}
+4
source share
2 answers

Looks nice.

He does the same for answers.

+8
source

Yes, this method ensures that implicit conversions are not allowed. However, this also means that this property does not arise from the definition only void func(string). So, to make this clear to readers, you could make it more self-sufficient 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){}
+1
source

All Articles