【问题标题】:Overloading standard C++ library functions inside a templated class file在模板化类文件中重载标准 C++ 库函数
【发布时间】: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&lt;&gt; 而不是我通常使用的 template&lt;class Type&gt;)。这些导致该类仅使用重载而从不使用标准 C++ 函数,并分别导致 no function template matches function template specialization 'to_string' 错误。

【问题讨论】:

  • 更好的方法就是不这样做。为什么不写一个会员MyClass::to_string?或重载operator&lt;&lt;以便可以流式传输
  • 不要试图将它塞进std 命名空间。您可以在自己的命名空间中定义一个 to_string,然后使用 using 声明以允许 getPrintLength 使用实际存在的任何重载。 Like so
  • @NathanPierson 谢谢!这很有帮助。我没想过要定义自己的名称空间(我还没有了解名称空间),但是您的示例很有意义。

标签: c++ c++11 tostring


【解决方案1】:

您可以为字符串输入编写一个单独的 to_string() 函数。编译器将负责根据输入类型调用您的 to_string() 或 std::to_string() 。

using namespace std;

string to_string(std::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();
}
int main(){
    myClass<int> myInt;
    myClass<std::string> var;
    cout<<myInt.getPrintLength(1235)<<endl;
    cout<<var.getPrintLength("StarRocket")<<endl;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-03
    • 2013-06-11
    • 1970-01-01
    • 1970-01-01
    • 2018-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多