为了测试并显示我的函数库的一些函数的结果,我创建了一组方便的函数。重载全局类型转换运算符
我有一个execute
功能,看起来像:
template <typename R, typename I>
std::string execute(const std::string& func_name, R(*func_ptr)(const I&), const I& func_input);
它调用的函数,并显示在一个格式化字符串,我可以向std::cout
结果和参数。
问题是,我的一些功能不返回可转换为字符串结果。我以为我可以简单的东西,如超载全球::operator std::string
:
template <typename T>
operator std::string(const std::vector<T>& v);
但是GCC抱怨:
error: 'operator std::string(const std::vector<T, std::allocator<_CharT> >&)' must be a nonstatic member function
嘛,当然问题是,我不能成员运营商加入到std::vector
,连服我的班级,我不想污染他们“测试”转换运营商。
我想我可以添加一个间接层并使用函数而不是转换操作符,但那不是更美观的解决方案。我也可以为std::ostream
重载::operator <<
并使用std::ostringstream
,但这也不是最干净的解决方案。
我想知道全局转换运算符是否真的不可重载,如果有,为什么。
但是许多运营商都可以作为全局或成员,何乐不为呢?例如,如果有一个全局和成员操作符<<,编译器会抱怨模糊的调用,它可能会对convertions做同样的事情。 – NewbiZ 2010-02-10 08:12:38
转换函数是特殊的成员函数(因为是构造函数,析构函数,OP =和拷贝构造),因为它们参与转化/对象创建。见12.3。 – dirkgently 2010-02-10 08:17:23