C++ : &(std::cout) as template argument

白昼怎懂夜的黑 提交于 2019-11-29 11:05:56
πάντα ῥεῖ

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

Live Demo


A more detailed explanation why can be found here:

Error with address of parenthesized member function

T.C.

Before C++17 removed this restriction, the syntactic form of a template argument for a pointer or reference template parameter was restricted. N4140 [temp.arg.nontype]/1.3 says that it must be

expressed (ignoring parentheses) as & id-expression, where the id-expression is the name of an object or function, except that the & may be omitted if the name refers to a function or array and shall be omitted if the corresponding template-parameter is a reference

(std::cout) isn't an id-expression. It's a primary-expression.

The "(ignoring parentheses)" part was added by Core issue 773, and is apparently meant to permit (&i), not &(i).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!