用于初始化指向实例化模板友元函数的指针的 C++ 语法

标签 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 */ }
};

最佳答案

感谢 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();
}

关于用于初始化指向实例化模板友元函数的指针的 C++ 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57262194/

相关文章:

c++ - 为什么将指针强制转换为数字类型是不安全的?

c++ - 文件索引

c++ - 每次我使用 placement new 分配时都会隐式调用析构函数

c++ - typedef 和 using 在语义上是等价的是什么意思?

C++ native Win32 简单编辑控件

c++ - C/C++ 覆盖数组边界

c++ - Visual Studio 如何将 boost::function 与/GR- 一起使用,而 GCC 不能与 -fno-rtti 一起使用?

c++ - (避免)在 C++ 中将代码拆分为 .cpp 和 .h 并进行高效编译

c++ - 在 C++ 中合并范围

c++ - 跨多个源文件使用全局(多次使用 extern)