Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/145.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 卡住---在C+中创建运算符模板+;_C++_Templates_Operators - Fatal编程技术网

C++ 卡住---在C+中创建运算符模板+;

C++ 卡住---在C+中创建运算符模板+;,c++,templates,operators,C++,Templates,Operators,我正在创建一个模仿cout的SpyOutput类,我正在尝试使用一个模板,这样我就不必重载错误消息的关键部分是“模板参数推断/替换失败”endl不是一个对象,它甚至不是一个函数。它是一个函数模板,是一个用来生成无限多个cookie函数的“cookie cutter”。当您的代码失败仅仅是因为std::endl是一个函数模板,因此编译器需要知道要使用哪个模板实例化。标准IOStream类为操纵器提供了单独的重载,并且它们显式地指定了模板实例化。您也可以这样做: SpyOutput& ope

我正在创建一个模仿cout的SpyOutput类,我正在尝试使用一个模板,这样我就不必重载错误消息的关键部分是“模板参数推断/替换失败”
endl
不是一个对象,它甚至不是一个函数。它是一个函数模板,是一个用来生成无限多个cookie函数的“cookie cutter”。当
您的代码失败仅仅是因为
std::endl
是一个函数模板,因此编译器需要知道要使用哪个模板实例化。标准IOStream类为操纵器提供了单独的重载,并且它们显式地指定了模板实例化。您也可以这样做:

SpyOutput& operator<<(std::ostream& (*manip)(std::ostream&))
{
    if (os) manip(*os);
    return *this;
}

SpyOutput&operator@Yakk:是的,重载问题只发生在函数中,值得发送到流的函数只有这三个,所以是的,只有这三个。因为它们都被指针所捕获,所以对它们的完美转发不是问题,尽管这可能是因为“主”过载。谢谢你的帮助!我认为这是模板的问题:S
main.cpp: In function 'int main()':
main.cpp:24:20: error: no match for 'operator<<' (operand types are 'SpyOutput' and '<unresolved overloaded function type>')
     spy << "Hello" << endl;
                    ^
main.cpp:24:20: note: candidates are:
main.cpp:13:16: note: template<class T> SpyOutput& SpyOutput::operator<<(T)
     SpyOutput& operator<<(T x)
                ^
main.cpp:13:16: note:   template argument deduction/substitution failed:
main.cpp:24:23: note:   couldn't deduce template parameter 'T'
     spy << "Hello" << endl;
                       ^
ostream& operator<< (ostream& (*pf)(ostream&));
ostream& operator<< (ios& (*pf)(ios&));
ostream& operator<< (ios_base& (*pf)(ios_base&));
//if T is a template, then T&& is a universal reference. A perfect match for everything
//if T were not a template, it would be an rvalue reference. Totally unrelated.
template <class T> SpyOutput& operator<<(T&& x) { 
    ss << x;
    *os << x;
    return *this;
}
SpyOutput& operator<<(std::ostream& (*manip)(std::ostream&))
{
    if (os) manip(*os);
    return *this;
}