重载函数不编译 [英] Overloading functions not compiling

查看:134
本文介绍了重载函数不编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注O'Reilly的C ++ Cookbook这本书,下面是代码:

I am following the book C++ Cookbook from O'Reilly and I try one of the examples, here is the code:

#include <string>
#include <iostream>
#include <cctype>
#include <cwctype>

using namespace std;

template<typename T, typename F>
void rtrimws(basic_string<T>& s, F f){
    if(s.empty())
        return;

    typename basic_string<T>::iterator p;
    for(p = s.end(); p != s.begin() && f(*--p););

    if(!f(*p))
        p++;

    s.erase(p, s.end());
}

void rtrimws(string& ws){
    rtrimws(ws, isspace);
}

void rtrimws(wstring& ws){
    rtrimws(ws, iswspace);
}

int main(){
    string s = "zing            ";
    wstring ws = L"zonh     ";

    rtrimws(s);
    rtrimws(ws);

    cout << s << "|\n";
    wcout << ws << "|\n";
}



当我尝试编译它,我得到以下错误

When I try to compile it, I get the following error

trim.cpp: In function ‘void rtrimws(std::string&)’:
trim.cpp:22: error: too many arguments to function ‘void rtrimws(std::string&)’
trim.cpp:23: error: at this point in file

我不明白有什么问题。如果我不使用char版本(字符串),但只使用wchar_t版本,一切运行顺利。

and I don't understand what's wrong. If I don't use the char version (string) but the wchar_t version only, everything runs smooth.

顺便说一下,我使用g ++ 4.4.3 ubuntu机器64位

By the way, I am using g++ 4.4.3 in an ubuntu machine 64 bits

推荐答案

isspace 接受一个模板字符以及一个locale,它使用facet std :: ctype< T> 来分类给定字符(因此它不能版本,因此忽略模板)。

isspace is also a template in C++ which accepts a templated character and also a locale with which it uses the facet std::ctype<T> to classify the given character (so it can't make up its mind what version to take, and as such ignores the template).

尝试指定您的意思是C兼容版本: static_cast< int(*)(int)>(isspace)。编译器之间的差异可能来自于编译器中重载函数名的不一致处理 - 参见 clang PR 。参见Faisal的第一组测试案例中的第二种情况。

Try specifying that you mean the C compatibility version: static_cast<int(*)(int)>(isspace). The differences between the compilers could come from the inconsistent handling of deduction from an overloaded function name among the compilers - see this clang PR. See the second case in Faisal's first set of testcases for an analogous case.

有人指出IRC这个代码会调用 isspace 使用 char - 但 isspace 需要 int 值给定在 unsigned char 值或 EOF 的范围内。现在如果 char 在您的PC上签名并存储了一个负的非EOF值,这将导致未定义的行为。

Someone pointed out on IRC that this code would call isspace using a char - but isspace takes int and requires the value given to be in the range of unsigned char values or EOF. Now in case that char is signed on your PC and stores a negative non-EOF value, this will yield to undefined behavior.

我建议像@Kirill在注释中说的,只是使用模板 std :: isspace 那么你可以摆脱的函数对象参数太。

I recommend to do it like @Kirill says in a comment and just use the templated std::isspace - then you can get rid of the function object argument too.

这篇关于重载函数不编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆