Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a legitimate method for making sure implicit type conversion does not happen

Tags:

c++

c++11

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;
}
like image 531
Adrian Cornish Avatar asked Jan 09 '23 12:01

Adrian Cornish


2 Answers

Looks good to me.

It does the same thing to answers.

like image 185
Edward Strange Avatar answered Jan 12 '23 01:01

Edward Strange


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){}
like image 21
Pradhan Avatar answered Jan 12 '23 01:01

Pradhan