首页 > 解决方案 > 用于初始化指向实例化模板友元函数的指针的 C++ 语法

问题描述

初始化指向实例化模板友元函数的指针的 C++ (14) 语法是什么?下面的最小示例。谢谢。

template <class template_param>
struct TYPE
{
  friend TYPE foo ( TYPE &, TYPE & ) { TYPE res; return res; }
  friend TYPE bar ( TYPE &, TYPE & ) { TYPE res; return res; }
};

struct CLASS
{
  typedef TYPE<int> (*ptr_to_function) ( TYPE<int>, TYPE<int> );

  ptr_to_function *  ptr_to_foo = foo; // What syntax is required here, or elsewhere,
  ptr_to_function *  ptr_to_bar = bar; // to set pointers to functions above?

  void calculate () {
    procedure ( ptr_to_bar );
    procedure ( ptr_to_foo );
  }

  void procedure ( ptr_to_function * fun ) { /* Use foo or bar via fun */ }
};

标签: c++

解决方案


感谢 HolyBlackCat,我对我的语法问题有了答案。aschepler 的观察只是导致将 foo 和 bar 放在单独的 .cpp 文件中。其余的评论对 SO 新手没有帮助。

...现在改回使用一个文件。

#include <iostream>

template <class T> struct TYPE;

template <class T> TYPE<T> foo(TYPE<T> &, TYPE<T> &);
template <class T> TYPE<T> bar(TYPE<T> &, TYPE<T> &);

template <class T>
struct TYPE
{
  friend TYPE<T> foo<> ( TYPE<T> &, TYPE<T> & );
  friend TYPE<T> bar<> ( TYPE<T> &, TYPE<T> & );
};

template <class T> TYPE<T> foo(TYPE<T> &, TYPE<T> &) { TYPE<T> res; std::cout << "1" << std::endl; return res; }
template <class T> TYPE<T> bar(TYPE<T> &, TYPE<T> &) { TYPE<T> res; std::cout << "2" << std::endl; return res; }

struct CLASS
{
  typedef TYPE<int> (*ptr_to_function) ( TYPE<int> &, TYPE<int> & );

  ptr_to_function  ptr_to_foo = foo<int>; // Initialise pointer to foo
  ptr_to_function  ptr_to_bar = bar<int>;

  void calculate () {
    procedure ( ptr_to_bar );
    procedure ( ptr_to_foo );
  }

  void procedure ( ptr_to_function fun )
  {
    TYPE<int> x;
    fun(x, x);
  }
};

int main()
{
    CLASS c;
    c.calculate();
}

推荐阅读