简体   繁体   中英

Operator overload in a templated method

I have a class (with irrelevant details stripped):

template <typename... Ts>
class ParameterPack
{
  private:
    std::tuple<Ts...> parameters;


  public:
    ParameterPack<Ts...>(const char* pVariableName)
    {
        /// Irrelevant extra details
    }


    template <typename T, std::size_t idx>
    T getValue()
    {
        return std::get<idx>(parameters);
    }


    template <std::size_t idx>
    void updateValue(unsigned int val)
    {
        std::get<idx>(parameters) = val;

        /// Irrelevant extra details
    }

template <class... Ts>
static ParameterPack<Ts...>* extractParameterPack(const char* name)
{
    // Construnt the new parameter extractor
    auto paramPack = new ParameterPack<Ts...>(name);

    /// Irrelevant extra details

    return paramPack;
}
};

Whose primary function is to parse a string into its data elements (held internally in a private tuple). I am trying to improve the ergonomics of the updateValue and getValue interface however.

I would like to overload [] to be to change the calling syntax from:

    auto val1 = parameterPack->getValue<float, 1>();

to:

    auto test2 = parameterPack[1];

But my overloads never take effect. I think the overload should look something close to:

or possibly:

    template <typename T, std::size_t idx>
    const T& operator[](std::size_t _idx) const
    {
        std::cout << "yay, overloading " << idx << std::endl;
        return idx * 1.0;
        // return std::get<idx>(parameters);
    }

If I call operator[] directly, it executes my overload, but not if I just try to use the [] operator normally.

It's not possible to specialize a templated operator[] on the index, since the index is a run-time property.

For this reason std::tuple has a get<idx>() member function instead of operator[] (see this related question ).

In addition, it's not possible to deduce a function (or operator) return type from an assignment.

So nether T nor idx in template <typename T, std::size_t idx> operator[]... can be deduced, unfortunately, which excludes it from the set of viable overload candidates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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