[英]Operator overload in a templated method
I have a class (with irrelevant details stripped):我有一个 class (删除了不相关的细节):
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).其主要 function 是将字符串解析为其数据元素(内部保存在私有元组中)。 I am trying to improve the ergonomics of the
updateValue
and getValue
interface however.但是,我正在尝试改进
updateValue
和getValue
接口的人体工程学。
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.如果我直接调用
operator[]
,它会执行我的重载,但如果我只是尝试正常使用[]
运算符则不会。
It's not possible to specialize a templated operator[]
on the index, since the index is a run-time property.由于索引是运行时属性,因此不可能在索引上专门化模板化
operator[]
。
For this reason std::tuple
has a get<idx>()
member function instead of operator[]
(see this related question ).出于这个原因,
std::tuple
有一个get<idx>()
成员 function 而不是operator[]
(参见这个相关问题)。
In addition, it's not possible to deduce a function (or operator) return type from an assignment.此外,不可能从赋值中推断出 function(或运算符)返回类型。
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.因此,不幸的是,
template <typename T, std::size_t idx> operator[]...
中的 Nether T
和idx
都可以推导出来,这将其排除在可行的重载候选集之外。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.