重载运算符<<接受模板功能 [英] Overloading operator<< to accept a template function

查看:80
本文介绍了重载运算符<<接受模板功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用函数编写可扩展的语法,但似乎找不到适合接受模板函数的正确语法.我正在使用Visual C ++2008.它将接受与模板函数具有相同类型的变量,或者接受类似的非模板函数,但模板函数本身不接受.

I'm trying to be able to write an extensible grammar using functions, but can't seem to find the right syntax for accepting a template function. I'm using Visual C++ 2008. It will accept a variable of the same type as the template function, or a similar non-template function, but not the template function itself.

错误1错误C2679:二进制'<<' :未找到采用'overloaded-function'类型的右操作数(或没有可接受的转换)的运算符(***行)

class Grammar {
    friend Grammar operator << ( const Grammar& lhs, const char* rhs ) {
        return lhs; // append rhs to grammar
    }
    template<typename T>
    friend Grammar operator << ( const Grammar& lhs, T (*rhs) () ) {
        return lhs; // append rhs() to grammar
    }
};

template<typename T>
class ExpressionParticle {
};

template<typename T>
ExpressionParticle<T> Expression () ;

ExpressionParticle<int> ExpressionInt ();

int _tmain ( int argc, _TCHAR *argv[] )
{
    ExpressionParticle<int> (*p)();

    p = Expression<int>;

    Grammar() << "p";
    Grammar() << p;
    Grammar() << ExpressionInt;
    Grammar() << Expression<int>; // ***

Expression<int>的类型不是上面p的类型吗?它的类型与ExpressionInt的类型有何不同.

What is the type of Expression<int> if it is not the type of p in above? How is its type different to the type of ExpressionInt.

推荐答案

您的代码对我来说还可以,而g ++也可以.这似乎是Visual Studio中怪异的重载解决程序错误. VS2005似乎有同样的问题.可能的解决方法是(已在VS2005中进行了测试):

Your code looks OK to me, and g++ is fine with that too. This seems to be weird overload resolution bug in Visual Studio. VS2005 seems to have the same problem. A possible workaround is (tested with VS2005):

template<class T>
T id(T t)  {return t; }
int main ()
{
    ExpressionParticle<int> (*p)();

    p = Expression<int>;

    Grammar() << "p";
    Grammar() << p;
    Grammar() << ExpressionInt;
    Grammar() << id(Expression<int>); // ***
}

这篇关于重载运算符&lt;&lt;接受模板功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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