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();
}
推荐阅读
- amazon-web-services - Apache Ubuntu 默认页面未加载
- java - 如何通过 SeleniumWebdriver 检索元素的 HTML?
- python - 为什么 keras 序列的实例会永远迭代?
- xaml - Xamarin Forms SetBinding 与可观察集合字典
- android - 将 ImageView 放在 TextView 下方
- apache - 在作为负载均衡器运行的 Apache 2.4 中配置基本身份验证
- php - 将 HTMl 表转换为 JSON + http://convertjson.com/html-table-to-json.htm
- ruby-on-rails - 如何将此 SQL 查询转换为 Rails 活动记录?
- mysql - MySql 表性能优化 - 哈希作为主键或唯一键
- python - tf.layers.conv2d 和 tf.contrib.slim.conv2d 的区别