Is it possible to use template
together with operator overload (not using template together with the class, but only with the specific operator such as operator[]
) in C++?
Here is an example (of course it can not be compiled pass).
class myClass
{
....
template<int i> auto operator[](std::string) -> std::tuple_element_t<t, types>
{
//some code here
}
...
}
int main()
{
myClass myObject;
....
auto a = myObject["rabbit"]<1>;
auto b = myObject["dog"]<2>;
...
}
Yes, it is possible, but the way you call it has to change. In order to specify the template parameter of operator[]
you need to call it with member function syntax like
myObject.operator[]<1>("rabbit");
Which really isn't very nice to look at. Instead, you could just use a named member function like get
and then use it like
class myClass
{
....
template<int i> auto get(std::string) -> std::tuple_element_t<t, types>
{
//some code here
}
...
}
auto a = myObject.get<1>("rabbit");
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.