2013-12-09 42 views
4

首先我应该指出这是我的第一个stackoverflow问题,所以请耐心等待。重载的函数歧义

我有一些问题在C++中重载函数。我试图创建一个函数具有以下原型:

void push_at_command(std::string, std::vector<std::string>, int); 

void push_at_command(std::string, std::vector<std::string>, std::vector<std::string>, int); 

void push_at_command(std::string, std::vector<std::string>, std::vector<std::string>, std::vector<std::string>, int); 

void push_at_command(std::string, std::vector<std::string>, bool, int); 

我本来想过去的过载(具有布尔)接受一个boost ::正则表达式,而不是一个字符串向量;

void push_at_command(std::string, boost::regex, int); 

但跑进歧义错误...所以只是快速获取代码“工作”我想我会添加一个原型接受一个标志,并使用第一个元素的载体来存储一个正则表达式字符串,但我似乎遇到了布尔类似的问题。

这是我正在努力把这些不同的重载:

push_at_command(
    "AT?S", 
    boost::assign::list_of("(\\d{3}.\\d{3})"), 
    true, 
    0); 
push_at_command(
    "AT?S", 
    boost::assign::list_of("L11")("L12"), 
    0); 
push_at_command(
    "AT?S", 
    boost::assign::list_of("L11"), 
    boost::assign::list_of("L21")("L22"), 
    0); 

这是我得到的错误:

error: call of overloaded ‘push_at_command(const char [5], boost::assign_detail::generic_list<char [4]>, boost::assign_detail::generic_list<char [4]>, int)’ is ambiguous 
note: candidates are: 
note: void push_at_command(std::string, std::vector<std::basic_string<char> >, std::vector<std::basic_string<char> >, int) 
note: void push_at_command(std::string, std::vector<std::basic_string<char> >, bool, int) 

...这涉及第三个功能呼叫。

只是要注意,我没有问题之前,我用bool添加重载(或将字符串向量更改为正则表达式)。

我假设这个问题与我在函数调用中使用boost :: assign有关,我意识到我不需要,但我真的需要'单线'函数调用。 ...任何意见的欢迎,因为我对C++来说是新手。

感谢

+2

我的个人建议:如果避免语法超载,你的生活会更快乐。 –

+0

感谢您的建议,我想您可能是对的! –

回答

2

的问题是,随着增压文档,But what if we need to initialize a container? This is where list_of() comes into play. With list_of() we can create anonymous lists that automatically converts to any container:

在看到在这种情况下,你不希望能够转换为任何容器,你要明确š载体。既然你有这个可转换类型,它不能决定它是否应该转换为布尔或向量,使呼叫模糊。

如果你真的想要继续你已经创建的重载集(请退后一步,并重新考虑你的方法使用一个标志),你需要专门分配一个向量列表(I' M}这里假设list_of提供了一个转换操作符向量):

push_at_command(
    "AT?S", 
    boost::assign::list_of("L11"), 
    std::vector<std::string>(boost::assign::list_of("L21")("L22")), 
    0); 
+0

但是如果你只保留使用bool的函数,你会得到 错误:从类型'std :: _ Deque_iterator < 。 这表明它不能转换为布尔 – yosim

+0

感谢您的建议,我现在重新组织和重新设计我的程序不使用这些重载。 –

2

错误消息告诉你的问题是什么。这是越来越陷入困境的调用是第三个:

push_at_command(
    "AT?S", 
    boost::assign::list_of("L11"), 
    boost::assign::list_of("L21")("L22"), 
    0); 

,问题是,它可以匹配push_at_command第三和第四版本。它们在第三个参数的类型上有所不同:一个采用vector,另一个采用bool

所以问题是boost::assign::list_of("L21")("L22)可以转换为vector它可以转换为bool,并且规则不喜欢其中一个转换。在这样的情况下,你必须帮助编译器,将static_cast设置为所需的类型。或者重新思考这些功能的组织结构,并且可能重新排列这些参数,以避免模棱两可。 (这就是为什么,例如std::string的构造函数需要(int, char),并且没有构造函数用于一个单独的char,这会导致含糊不清;这是一个尴尬的接口,由过多的重载驱动)。

+0

请看我对Mark B的问题。它也与你的答案有关。 – yosim