具有不同亚型的参数方法
Parametric methods with different subtypes
今天在编程语言课中,我们在Java中看到了这种行为:
public class Es {
...
<Y> Y choose(Y y1, Y y2){
Y returnVal;
if("some test"){ returnVal = y1;} else{ returnVal = y2;}
return returnVal;
}
}
主要:
Es c = new Es();
Integer i = 3;
Float f = (float) 4.5;
Number n = c.choose(i, f);
"令人难以置信的"是该方法必须在整数和float之间选择参数类型y并选择最近的超级类型,即数字。
我想在C 中重现它,但我被卡住了...
模板在不匹配时不要尝试调整类型。这就是为什么简单实现如下的原因:
template <class Y>
Y choose(Y y1, Y y2) {
// ...
}
失败了以下错误:
main.cpp:8:5: fatal error: no matching function for call to 'choose'
choose(1, 2.5f);
^~~~~~
main.cpp:3:3: note: candidate template ignored:
deduced conflicting types for parameter 'Y' ('int' vs. 'float')
您想做的是让函数模板两种类型,然后然后解析公共类型:
template <class Y1, class Y2>
auto choose(Y1 y1, Y2 y2) {
using Y = std::common_type_t<Y1, Y2>;
Y returnVal;
if("some test") {
returnVal = y1;
} else {
returnVal = y2;
}
return returnVal;
}
一个好主意是通过将类型的扣除额提升为签名来使功能对Sfinae友好:
template <class Y1, class Y2>
std::common_type_t<Y1, Y2> choose(Y1 y1, Y2 y2) {
// Same as before
}
使用模板函数。与Java代码相同的C 代码实际上与Java代码非常相似:
:template <typename Y>
Y choose(Y y1, Y y2) {
Y returnVal;
if("some test"){ returnVal = y1;} else{ returnVal = y2;}
return returnVal;
}
您可以像在Java中那样称呼它 - 编译器将推断出正确的类型:
choose(1,2); //With two ints
choose("hi","bye"); //With two char*s.
注意:语义上,C 模板与Java Generics完全不同。JAVA通用物是使用类型擦除实现的 - JRE不知道运行时类型参数,而C 模板实际上每次将模板用于其他类型时创建单独的函数或类。看到此答案。
编辑:我误解了您的问题。如果不考虑,我认为C 没有您想要的行为。您必须明确指定两者都是超级型。
相关文章:
- 使用在用于SFINAE的void_t中具有参数的方法
- 如何制作一个将函数作为参数的类方法
- c++方法参数只能在linux的发布模式下自行更改
- 使用用户定义的参数调用future/async并调用类方法
- 将成员函数指针作为参数传递给模板方法
- 在 cpp 文件中隐藏采用模板参数引用的方法
- 使用模板参数重载C++方法:如何使其适用于模板的子类?
- 具有字符串化的可变参数宏的现代/通用方法
- 在 C++ 中将非指定类型作为参数传递的最佳方法?
- 如何在方法中传递结构参数
- 如何将类成员方法的参数列表自动填充写入可变参数?
- C++有什么方法可以在既不调用函数模板也不提供其模板参数的情况下引用函数模板?
- C++方法是否可以根据传递给构造函数的参数具有不同的返回类型?
- C++接口继承不同的参数方法
- C++ 模板:重载时找不到基类类型参数方法
- 如何使用迭代器作为参数方法?
- 具有不同亚型的参数方法
- 如何以相同的方法在子类中超载的相同方法来实现工作变量参数方法
- 如何将 C 中声明的可选参数方法转换为 c++
- 如果模板化"ResourceCache"需要不同的创建参数/方法,它们如何加载/创建 T 类型的资源?