Gae*_*eul 5 c++ templates cout c++11
为什么不能将std::cout地址作为模板参数传递?或者如果有可能那么如何?
这是我尝试过的:
#include <iostream>
template<std::ostream* stream>
class MyClass
{
public:
void disp(void)
{ (*stream) << "hello"; }
};
int main(void)
{
MyClass<&(std::cout)> MyObj;
MyObj.disp();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我得到的错误信息clang++ -std=c++11:
main.cpp:15:11: error: non-type template argument does not refer to any declaration
MyClass<&(std::cout)> MyObj;
^~~~~~~~~~~
main.cpp:6:24: note: template parameter is declared here
template<std::ostream* stream>
^
1 error generated.
Run Code Online (Sandbox Code Playgroud)
来自g++ -std=c++11:
main.cpp: In function ‘int main()’:
main.cpp:15:22: error: template argument 1 is invalid
MyClass<&(std::cout)> MyObj;
^
main.cpp:15:29: error: invalid type in declaration before ‘;’ token
MyClass<&(std::cout)> MyObj;
^
main.cpp:16:8: error: request for member ‘disp’ in ‘MyObj’, which is of non-class type ‘int’
MyObj.disp();
^
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
这修复了您的代码,省略括号:
#include <iostream>
template<std::ostream* stream>
class MyClass
{
public:
void disp(void) {
(*stream) << "hello";
}
};
int main(void)
{
MyClass<&std::cout> MyObj;
MyObj.disp();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
更详细的解释可以在这里找到: