【发布时间】:2022-12-05 03:44:01
【问题描述】:
我正在尝试将 std::to_string() 函数重载到它可以将字符串作为参数并仅返回字符串的位置,与模板类位于同一文件中。这样它就可以被成员函数使用。但这让我犯了错误:out-of-line definition of 'to_string' does not match any declaration in namespace 'std'
这是我想要的通用版本:
#include <string>
using namespace std;
string std::to_string(string str){return str;}
template <class Type>
class myClass
{
public:
int getPrintLength(Type var);
};
template <class Type>
int myClass<Type>::getPrintLength(Type var)
{
return to_string(var).size();
}
对于上下文,我这样做是为了通过 to_string(var).size() 获取变量(任何标准类型)在打印时将具有的字符数,包括 string,这需要函数将字符串作为参数(所以我不必检查变量是什么类型)。
但当然,可能有更好的方法来做到这一点,我对此持开放态度。
我尝试过使用不同的范围,并为我的 to_string() 重载设置模板(使用 template<> 而不是我通常使用的 template<class Type>)。这些导致该类仅使用重载而从不使用标准 C++ 函数,并分别导致 no function template matches function template specialization 'to_string' 错误。
【问题讨论】:
-
更好的方法就是不这样做。为什么不写一个会员
MyClass::to_string?或重载operator<<以便可以流式传输 -
不要试图将它塞进
std命名空间。您可以在自己的命名空间中定义一个to_string,然后使用using声明以允许getPrintLength使用实际存在的任何重载。 Like so。 -
@NathanPierson 谢谢!这很有帮助。我没想过要定义自己的名称空间(我还没有了解名称空间),但是您的示例很有意义。