繁体   English   中英

在模板化的 class 文件中重载标准 C++ 库函数

[英]Overloading standard C++ library functions inside a templated class file

我正在尝试将std::to_string() function 重载到它可以将字符串作为参数并仅返回字符串的位置,与模板化的 class 在同一文件中。这样它就可以被成员函数使用。 但这让我犯了一个错误: 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 ,这需要 function 来获取字符串作为参数(所以我不必检查变量是什么类型)。

但当然,可能有更好的方法来做到这一点,我对此持开放态度。

我尝试过使用不同的范围,并为我的to_string()重载设置模板(使用template<>而不是我常用的template<class Type> )。 这些导致 class 简单地使用重载而从不使用标准 C++ function,并且no function template matches function template specialization 'to_string'错误。

可以单独写一个to_string() function 用于字符串输入。 编译器将负责根据输入类型调用您的 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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM