C ++:&(std :: cout)作为模板参数 [英] C++ : &(std::cout) as template argument

查看:157
本文介绍了C ++:&(std :: cout)作为模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不能通过 std :: cout 的地址作为模板参数?
还是可能的话怎么办?

Why isn't it possible to pass std::cout's address as template argument? Or if it is possible then how?

这是我尝试过的内容:

#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;
}

我从 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.

并来自 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();
        ^

有任何想法吗?

推荐答案

这会修复代码,省略括号:

This fixes your code, omit the parenthesis:

#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;
}

实时演示

为什么可以在这里找到更详细的解释:

A more detailed explanation why can be found here:

带括号的成员函数的地址错误

这篇关于C ++:&amp;(std :: cout)作为模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆