我一直认为,使用模板化函数,不可能发生隐式转换,并且参数的类型必须与参数的模板化类型完全匹配,否则模板参数推导会失败。
嗯,看来我弄错了。
考虑以下代码段:
#include <iostream>
#include <type_traits>
template <class T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
class myInt
{
T val;
public:
myInt(T val) : val(val) {}
template <class U, typename = typename std::enable_if<std::is_integral<U>::value>::type>
friend bool operator < (myInt<T> const &t, myInt<U> const &u)
{
return t.val < u.val;
}
};
int main()
{
myInt<int> i = 5;
myInt<int> j = 6;
// std::cout << (i < 6) << std::endl; // gives out compiler errors
std::cout << (5 < j) << std::endl; // works!
}
我不知道为什么第二个std::cout << (5 < j)
工作。这里肯定发生了隐式转换,我认为这是被禁止的。而且我更不确定为什么std::cout << (i < 6)
如果前一个可以工作,为什么不工作!
编辑:编译器错误std::cout << (i < 6)
:
test.cpp: In function ‘int main()’:
test.cpp:23:21: error: no match for ‘operator<’ (operand types are ‘myInt<int>’ and ‘int’)
std::cout << (i < 6) << std::endl; // gives out compiler errors
^
test.cpp:23:21: note: candidate is:
test.cpp:12:17: note: template<class U, class> bool operator<(const myInt<int>&, const myInt<T>&)
friend bool operator < (myInt<T> const &t, myInt<U> const &u)
^
test.cpp:12:17: note: template argument deduction/substitution failed:
test.cpp:23:23: note: mismatched types ‘const myInt<T>’ and ‘int’
std::cout << (i < 6) << std::endl; // gives out compiler errors