I am writing a class in which I am overloading operator[]
and I want one function to have vector as input and the second one to have vector of vectors as input, but when I call it like
obj[{ 0 }]
then I got ambigious call error. The functions are declared like
const Tensor operator[](const std::vector<std::vector<uint32_t>>& ranges) const;
const float operator[](const std::vector<uint32_t>& index) const;
Is there any way to handle that ambiguity?
CodePudding user response:
The compiler has no way of knowing by seeing the argument {0}
which one to choose among the two equally ranked overloads.
One way to resolve the ambiguity is to explicitly tell the compiler as shown below:
obj[std::vector<uint32_t>{0}]; //calls #2
obj[std::vector<std::vector<uint32_t>>{0}]; //calls #1
If you want to make it more readable you have the option of using typedef
or using
as shown below:
struct Tensor
{
//so that we don't have to type these again and again
using vec = std::vector<uint32_t>;
using vec2D = std::vector<std::vector<uint32_t>>;
//the two overloads here(below)
};
int main()
{
Tensor obj;
obj[Tensor::vec{0}]; //calls #2
obj[Tensor::vec2D{0}]; //calls #1
}
CodePudding user response:
{0}
has no type. and it is valid to construct both std::vector<uint32_t>
and std::vector<std::vector<uint32_t>>
(without overload resolution preference).
You might specify the type explicitly at call site:
obj[std::vector<uint32_t>{0}];
obj[std::vector<std::vector<uint32_t>>{0}];
or add extra overload with higher priority:
Tensor operator[](const std::vector<std::vector<uint32_t>>& ranges) const;
float operator[](const std::vector<uint32_t>& index) const;
float operator[](const std::initializer_list<uint32_t>& ini) const
{
return operator[](std::vector(ini));
}
CodePudding user response:
I'm not sure I understand the question but I think you should cast your variable.
(type)variable