SFINAE与运营商<<

时间:2016-09-29 17:11:16

标签: c++ operator-overloading sfinae

该程序演示了两次尝试使用SFINAE。一个按预期工作,另一个没有:

#include <iostream>
using namespace std;

struct Example {
    typedef int type;
};

template <typename T>
void foo(typename T::type t) {
    cout << "Function 1 is called" << endl;
}

template <typename T>
void foo(T t) {
    cout << "Function 2 is called" << endl;
}

class Stream {
public:
    template <typename T>
    Stream& operator <<(typename T::type t) {
        cout << "Function 3 is called" << endl;
        return *this;
    }

    template <typename T>
    Stream& operator <<(T t) {
        cout << "Function 4 is called" << endl;
        return *this;
    }
};

int main()
{
    // SFINAE works as expected
    foo<Example>(10);   // Prints "Function 1 is called"
    foo<int>(10);       // Prints "Function 2 is called"

    // SFINAE doesn't work as expected
    Stream strm;
    strm << Example();  // Prints "Function 4 is called"
    strm << 10;         // Prints "Function 4 is called"

    return 0;
}

如上所述:

  

函数1被称为

     

函数2被称为

     

函数4被称为

     

函数4被称为

有人可以解释为什么行

  

strm&lt;&lt;例();

不打印&#34;功能3被称为&#34;?我该怎么做才能实现呢?

0 个答案:

没有答案