0

我一直认为,使用模板化函数,不可能发生隐式转换,并且参数的类型必须与参数的模板化类型完全匹配,否则模板参数推导会失败。

嗯,看来我弄错了。

考虑以下代码段:

#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
4

1 回答 1

1

U这是“不对称”的原因是这之间存在根本区别T

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);

operator<是一个模板,并且U是这个模板的一个参数。但T不是此模板的参数。T实际上是一个不同模板的参数,myInt因此T=int在这个上下文中是固定的(到)。

实际上,你有这个:

template <class U, /*SFINAE stuff*/>
friend bool operator < (myInt<int> const &t, myInt<U> const &u);

鉴于(5 < j)它确实知道如何转换5myInt<int> const &for t。它可以通过推断j= `int.myInt<int>myInt<U> const &uU

(j<6)不起作用,因为它不知道如何传递6template<class U> ..... myInt<U> const &u. 特别是,它怎么能猜出哪个U会创建一个合适myInt<U>的带有必要的构造函数呢?也许myInt<int>有一个string构造函数,并且myInt<string>有一个int构造函数!编译器无法知道。


我认为你可以这样做:

/*   *NOT* a template */
friend bool operator < (myInt<T> const &t, myInt<T> const &u);
                         T instead of U ~~~~~~~~~^
于 2015-08-07T11:16:11.100 回答