如何使用auto关键字在C++ 11中返回任意类型?

jlc*_*lin 1 c++ auto c++11

我有一个看起来像这样的课程:

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;
};
Run Code Online (Sandbox Code Playgroud)

我想重载operator[]函数以从任何一个DoublesIntegers根据传递的键返回一些东西.但是,如果要归还的是a 或a ,我不知道prioi.我想以这种方式实现这个功能:doubleintoperator[]

// 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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法创建一个operator[]函数来返回多种类型?

这是由这个简单的代码驱动的:

int main(){

    Container Bucket;

    double pi(Bucket["pi"]);

    std::cout << "The value of pi is: " << pi << std::endl;

    return 0;
 }
Run Code Online (Sandbox Code Playgroud)

T.C*_*.C. 7

auto返回类型的C++ 11版本只允许您推迟返回类型声明,直到声明了函数参数:

template<typename T1, typename T2>
auto add(T1 x, T2 y) -> decltype(x + y) { return x + y; }
Run Code Online (Sandbox Code Playgroud)

在这里你不能写,decltype(x + y) add(...)因为编译器不知道是什么xy是什么.

auto许可证的C++ 14版本由编译器返回类型推导.它告诉编译器根据正文推导出函数的返回类型,但它仍然是单一的返回类型,所以它仍然没有做你想要的.


Wyz*_*a-- 7

不,你做不到.函数必须具有在编译时已知的单一返回类型; 当编译器可以从上下文中找出它必须是什么时,auto只是让你不必输入它.

您可以使用标记的联合或包含Boost.Variant之类的类来根据运行时决策保存不同类型的值.这可以为您提供具有可更改返回类型的效果.