简体   繁体   English

std :: get以元组为成员的自己的类

[英]std::get for own class with tuple as member

I have a class like this: 我有这样的课:

 template<typename ... TTypes>
 class Composite {
 public:
     std::tuple<TTypes...> &getRefValues() { return values; }   
 private:
     std::tuple<TTypes...> values;
 };

Can I define std::get for my class Composite? std::get为类Composite定义std::get吗? It should basically call the already defined std::get for the private tuple values. 它基本上应该调用已定义的std::get作为私有元组值。

I was able to implement a customized get function when the return type is known (eg for an int array member) but I don't know how to realize get when the return type can be an arbitrary type (depending on the components' type of the tuple values)? 当返回类型已知时(例如对于int数组成员),我能够实现自定义的get函数,但是当返回类型可以是任意类型时(取决于组件的类型),我不知道如何实现get元组值)?

You may do: 您可以这样做:

template <std::size_t I, typename... Ts>
auto get(Composite<Ts...>& composite)
-> decltype(std::get<I>(composite.getRefValues()))
{
    return std::get<I>(composite.getRefValues());
}

Note: In C++14, you may omit the -> decltype(..) part. 注意:在C ++ 14中,您可以省略-> decltype(..)部分。

For completeness, here is my solution. 为了完整起见,这是我的解决方案。 Thanks everyone: 感谢大家:

template<typename ... TTypes>
class Composite {
public:
    Composite(TTypes... t) {
        std::tuple<TTypes...> tuple(t...);
        values = tuple;
    } 

    std::tuple<TTypes...> &getRefValues() { return values; }    
private:
    std::tuple<TTypes...> values;
};

namespace std {
template<size_t I, typename ... TTypes>
    auto get(Composite<TTypes ...> &t) -> typename std::tuple_element<I, std::tuple<TTypes...>>::type { 
        return std::get<I>(t.getRefValues());
    }
}

int main() {
    Composite<int, char, double> c(13, 'c', 13.5);
    std::cout << std::get<0>(c) << std::endl;
    std::cout << std::get<1>(c) << std::endl;
    std::cout << std::get<2>(c) << std::endl;

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM