如何使用auto关键字在C ++ 11中返回任意类型? [英] How to return arbitrary type in C++11 using auto keyword?
问题描述
我有一个类如下所示:
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
或整数
返回某个值,具体取决于传递的键。但是,如果返回的是 double
或 int $ c,我不知道 $ c>。我想以这种方式实现
运算符[]
函数:
I'd like to overload the operator[]
function to return something from either Doubles
or Integers
depending on a key that is passed. However, I don't know a prioi if what will be returned is a double
or a int
. I'd like to implement the operator[]
function in this way:
// 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;
}
}
}
方法来创建单个运算符[]
函数以返回多个类型?
Is there a way to create a single operator[]
function to return multiple types?
这个简单的代码:
int main(){
Container Bucket;
double pi(Bucket["pi"]);
std::cout << "The value of pi is: " << pi << std::endl;
return 0;
}
推荐答案
auto
作为返回类型只允许推迟返回类型声明,直到声明函数参数之后:
The C++11 version of auto
as return type only allows you to postpone the return type declaration until after the function parameters have been declared:
template<typename T1, typename T2>
auto add(T1 x, T2 y) -> decltype(x + y) { return x + y; }
在这里你不能写 decltype(x + y)add ...)
,因为编译器不知道 x
和 y
是什么。
Here you can't write decltype(x + y) add(...)
because the compiler doesn't know what x
and y
are.
auto
的C ++ 14版本允许编译器返回类型的扣除。它告诉编译器基于body来推导函数的返回类型,但它仍然是一个返回类型,所以它仍然不能做你想要的。
The C++14 version of auto
permits return type deduction by the compiler. It tells the compiler to deduce the return type of the function based on the body, but it's still a single return type, so it still does not do what you want.
这篇关于如何使用auto关键字在C ++ 11中返回任意类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!