문제

I am trying to learn C++11/14 new features and I am playing with tuple and variadic. I wonder if it is possible to use tuples to return multiple values that are not fixed at compile time.

Something like (not working code):

template <typename... Ts>
std::tuple<Ts...> get(bool f) {
    if(f)
        return std::make_tuple("Hello", 1, 4.2);
    else
        return std::make_tuple(3.3, 'i');
}

I also read about auto return deduction, but it can be used only when all return have the same type.

도움이 되었습니까?

해결책

The short answer is that no it is not. The compiler can do some type deduction to figure out the return type without your specifying it explicitly (at least in some cases), but in every case the type itself must be fixed at compile time.

In theory, you could (for example) return something like an std::vector<boost::any> to allow returning an arbitrary number of arbitrary types. I'd caution, however, that this is likely to be more of a problem than a solution. To be useful, you nearly always want to place tighter constraints than that.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 softwareengineering.stackexchange
scroll top