英文:
C++ equivalent of using Entry<? extends ClassA, ? extends ClassB> getEntries() for more than two java parameter
问题
在Java中,我有一个方法:
```java
Set<? extends Entry<? extends ClassA, ? extends ClassB>> getEntries();
我已经阅读了关于https://stackoverflow.com/questions/30687305/c-equivalent-of-using-t-extends-class-for-a-java-parameter-return-type的问题,
我尝试如下:
template<typename K, typename std::enable_if<std::is_base_of<ClassA, K>::value>::type* = nullptr, typename V, typename std::enable_if<std::is_base_of<ClassB, V>::value>::type* = nullptr> set<pair<K,V>> getEntries()
它可以成功编译,但我认为这样写太冗长,而且可能是错误的。我想知道是否有更好的解决方案。
<details>
<summary>英文:</summary>
In java, I have a method:
```java
Set<? extends Entry<? extends ClassA, ? extends ClassB>> getEntries();
I have read the question about https://stackoverflow.com/questions/30687305/c-equivalent-of-using-t-extends-class-for-a-java-parameter-return-type,
I try as follow :
template<typename K, typename std::enable_if<std::is_base_of<ClassA, K>::value>::type* = nullptr, typename V, typename std::enable_if<std::is_base_of<ClassB, V>::value>::type* = nullptr> set<pair<K,V>> getEntries()
it compile well, but I think it's lengthy and perhaps wrong. I wonder whether there is a better solution.
答案1
得分: 0
你只需要将链接的解决方案调整为适用于你的情况。你的尝试(来自评论)并不完全正确。在使用enable_if
与模板参数时,它应该是最后一个参数,并且只应出现一次。因此,修改你的代码,将V
移到enable_if
之前,并将enable_if
改为使用&&
,你会得到:
template<typename K, typename V, typename std::enable_if<std::is_base_of<ClassA, K>::value && std::is_base_of<ClassB, V>::value>::type * = nullptr>
std::set<std::pair<K, V>> getEntries();
虽然不太美观,但你可以使用enable_if_t
,这样就不需要::type
,但节省的空间不会太多。示例:
template<typename K, typename V, typename std::enable_if_t<std::is_base_of_v<ClassA, K> && std::is_base_of_v<ClassB, V>> * = nullptr>
std::set<std::pair<K, V>> getEntries();
英文:
You just need to adapt the linked solution to work for yours. Your attempt (from the comments) isn't quite correct. When using enable_if
with template parameters, it should be the last parameter, and should only appear once. So, modifying what you did to move V
before the enable_if
, and changing the enable_if
to use an &&
, you get:
template<typename K, typename V, typename std::enable_if<std::is_base_of<ClassA, K>::value && std::is_base_of<ClassB, V>::value>::type * = nullptr>
std::set<std::pair<K, V>> getEntries();
It's not pretty, ever. You can use enable_if_t
so you don't need ::type
, but you won't save too much space. Example:
template<typename K, typename V, typename std::enable_if_t<std::is_base_of_v<ClassA, K> && std::is_base_of_v<ClassB, V>> * = nullptr>
std::set<std::pair<K, V>> getEntries();
专注分享java语言的经验与见解,让所有开发者获益!
评论