为每个函数和自由函数增强mpl
Boost mpl for each and free functions
为什么这段代码不能编译:
#include <boost/mpl/vector.hpp>
#include <boost/mpl/for_each.hpp>
#include <iostream>
using namespace std;
using namespace boost;
template <class T> // specific visitor for type printing
static void print_type(T t)
{
std::cout << typeid(T).name() << std::endl;
}
typedef mpl::vector<int, long, char*> s;
int main ()
{
mpl::for_each<s>(print_type());
}
我想知道-如何使boost mpl for_each工作与同一类的自由函数?
如上所述,您需要一个函子。
下面的代码包含一个额外的换行模板,该模板允许print函函数处理引用。
#include <iostream>
#include <typeinfo>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/for_each.hpp>
#include <boost/mpl/placeholders.hpp>
using namespace std;
using namespace boost;
template <typename T>
struct wrap {};
struct print_type
{
template< typename T>
void operator()( wrap<T> ) const
{
cout << typeid(T).name() << "n";
}
};
typedef mpl::vector<int, long&, char*> s;
int main ()
{
mpl::for_each<s, wrap<mpl::placeholders::_1> >(print_type());
return 0;
}
注意:此代码基于David Abrahams和Aleksy Gurtovoy所著的《c++ Template Metaprogramming》中的示例
mpl::for_each<s>(print_type());
这在几个方面都是错误的。
首先,print_type
是一个返回void
的函数。print_type()
尝试调用该函数。因为它不返回任何东西,所以你不能把它不存在的返回值插入到其他东西中。
第二,print_type
是模板函数。如果不指定模板参数,就不能调用模板函数。所以print_type()
是病态的
第三,即使mpl::for_each<s>(print_type)
也不起作用,因为print_type
不是一个值(也不能转换为一个值);它是一个模板。不能将模板作为函数的参数传递。这就是为什么访问者(对于很多东西,不仅仅是MPL)是对象,它可以有模板operator()
成员。
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- Python ctypes,回调函数增强类型是C++参考
- 连接来自未知类的成员函数以增强信号
- 崩溃:分段故障:增强序列化加载 - 用null调用构造函数
- 传递Python函数以增强C
- 增强 C++ 函数以除了 std::string 之外还采用 stringstream
- 为每个函数和自由函数增强mpl
- 增强type_erasure any与const成员函数
- 在另一个函数中增强读/写锁