【发布时间】:2014-05-23 14:23:38
【问题描述】:
我有一个如下所示的课程:
class Container {
public:
Container(){
Doubles["pi"] = 3.1415;
Doubles["e"] = 2.7182;
Integers["one"] = 1;
Integers["two"] = 2;
}
// Bracket.cpp:23:9: error: 'auto' return without trailing return type
// auto& operator[](const std::string&);
auto& operator[](const std::string& key);
private:
std::map<std::string, double> Doubles;
std::map<std::string, int> Integers;
};
我想重载operator[] 函数以根据传递的键从Doubles 或Integers 返回一些内容。但是,我不知道优先返回的是double 还是int。我想用这种方式实现operator[]函数:
// Compiler error
// Bracket.cpp:30:1: error: 'auto' return without trailing return type
// auto& Container::operator[](const std::string& key){
auto& Container::operator[](const std::string& key){
std::cout << "I'm returning the value associated with key: "
<< key << std::endl;
auto D_search = Doubles.find(key);
if (D_search != Doubles.end()){
std::cout << "I found my key in Doubles with value: " <<
D_search->second << std::endl;
return D_search->second;
}
else{
auto I_search = Integers.find(key);
if (I_search != Integers.end()){
std::cout << "I found my key in Integers with value: " <<
I_search->second << std::endl;
return I_search->second;
}
else{
std::cout << "I didn't find a value for the key." << std::endl;
}
}
}
有没有办法创建一个operator[] 函数来返回多种类型?
这是由这个简单的代码驱动的:
int main(){
Container Bucket;
double pi(Bucket["pi"]);
std::cout << "The value of pi is: " << pi << std::endl;
return 0;
}
【问题讨论】:
-
您不能仅根据返回类型重载。
-
auto并不是突然允许函数具有多种返回类型的某种黑魔法。在这种情况下,由于int可以转换为double,您可以只返回后者,但一般来说,您要求的内容是不可能的。创建单独的函数,或者如果您必须有一个函数,则返回 Boost.Variant 或类似的东西。