这是确保不会发生隐式类型转换的合法方法吗

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

本文关键字:类型转换 方法 确保      更新时间:2023-10-16

这是确保不发生隐式类型转换的合法方法吗?

#include <string>
#include <iostream>
void func(std::string s)
{
   std::cout << "Thanks for the stringn";
}
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;
}

我觉得不错。

它对答案也有同样的作用。

是的,该方法确保不允许隐式转换。然而,这也意味着这个性质并不是单独由void func(string)的定义产生的。因此,为了向读者澄清这一点,您可以使其更加独立,如下所示:

template <typename T, typename U> using RequireExplicit = enable_if_t<is_same<T, U>>;
template <typename T, typename = RequireExplicit<T, string>>
void func(T){}