【发布时间】:2011-01-15 04:00:25
【问题描述】:
为了测试和显示我库中某些函数的结果,我正在创建一组方便的函数。
我有一个 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的格式化字符串显示结果和参数。
问题是我的一些函数没有返回 convertible-to-string 结果。我想我可以简单地重载全局 ::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,但这也不是最干净的解决方案。
我想知道全局转换运算符是否真的不可重载,如果是,为什么。
【问题讨论】:
标签: c++ operators operator-overloading