代码之家  ›  专栏  ›  技术社区  ›  deft_code

什么是对函数的左值引用?

  •  1
  • deft_code  · 技术社区  · 16 年前

    在§新的C++ 0x标准描述了作为模板参数允许的非类型。

    4) 非类型 模板参数 简历合格

    • 整数或枚举类型,
    • 指向对象或函数的指针,
    • 指向成员的指针。

    我想要这样的东西:

    //pointer to function
    typedef int (*func_t)(int,int);
    
    int add( int lhs, int rhs )
    { return lhs + rhs; }
    
    int sub( int lhs, int rhs )
    { return lhs - rhs; }
    
    template< func_t Func_type >
    class Foo
    {
    public:
       Foo( int lhs, int rhs ) : m_lhs(lhs), m_rhs(rhs) { }
    
       int do_it()
       {
          // how would this be different with a reference?
          return (*Func_type)(m_lhs,m_rhs);
       }
    private:
       int m_lhs;
       int m_rhs;
    };
    
    int main()
    {
       Foo<&add> adder(7,5);
       Foo<&sub> subber(7,5);
    
       std::cout << adder.do_it() << std::endl;
       std::cout << subber.do_it() << std::endl;
    }
    
    1 回复  |  直到 16 年前
        1
  •  3
  •   James McNellis    16 年前

    你的 func_t

    typedef int (&func_t)(int, int);
    

    然后你的 main()

    int main()
    {
        Foo<add> adder(7,5);
        Foo<sub> subber(7,5);
    
        std::cout << adder.do_it() << std::endl;
        std::cout << subber.do_it() << std::endl;
    }