CAN模板类型推理考虑原始操作类型转换
Can template type inference take primitive operation type conversions into account?
模板似乎无法键入原始操作的结果。例如,以下未能推断出R:
template<typename A, typename B, typename R>
R addNumbers(A x, B y){
return x + y;
}
main(){
addNumbers(1.0f, 1);
}
即使很明显float + int = float
。
在任何版本的C 中,是否有某种方法可以将这些信息考虑到而无明确指定的推断?
模板参数扣除时,呼叫函数时无法注视函数的主体;它只是试图使函数的参数类型与参数类型相同,而无法推导这种方式的任何模板参数都不会固定。您需要一种基于功能正文中的返回语句的推论形式。这由auto
在C 14中提供:
template<typename A, typename B>
auto addNumbers(A x, B y){
return x + y;
}
decltype
是C 11中最好的添加之一。阅读更多有关它的信息:http://en.cppreference.com/w/cpp/language/decltype
C 11的解决方案(使用编译器标志-std=c++11
(
template<typename A, typename B>
auto addNumbers(A const & x, B const & y) -> decltype(x + y)
{
return x + y;
}
decltype
最好的部分,您几乎可以在其中写入任何表达式,并且将在编译时进行评估。
在上面的示例中,我们要求编译器通过评估其类型来声明函数的返回类型,与表达式x + y
的返回型相同。
C 14的解决方案(不需要decltype
,使用Compiler Flag -std=c++14
(
template<typename A, typename B>
auto addNumbers(A const & x, B const & y)
{
return x + y;
}
用法:
auto ans = addNumbers(1.0f, 1); // ans is deduced to be float
功能过载扣除额,无论是否考虑模板,都不会并且不能考虑返回类型。返回型不是函数签名的一部分。扣除仅考虑呼叫的参数是否匹配各种函数声明的参数。以下将匹配任何A和A。如果定义了operator+ (A, B)
,则返回类型将是返回的任何内容。如果未定义operator+ (A, B)
,则编译器将丢弃错误。
template<typename A, typename B>
auto addNumbers(A x, B y){
return x + y;
}
int main(){
addNumbers(1.0f, 1);
}
相关文章:
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 重载操作程序时出错>>用于类中的字符串 memebr
- 对字符串进行位操作
- 将浮动的heightmap数组导出为16位原始值
- 给定一个向量,如何找到该向量的所有子集和的原始索引
- 我可以在 C++ 中的函数体之外进行操作吗?
- MPI突然停止了对多个核心的操作
- 有没有办法从非C/C++文件中读取C++原始字符串文字的内容
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- C++:将值赋值给原始数据类型(例如布尔值)是原子操作吗?
- 我想知道像素/片段的原始模板值.零还是一个?如果可能的话,以获取哪些特定操作会修改模板值
- CAN模板类型推理考虑原始操作类型转换
- 打开一个文件,修改每个字符,然后执行反向操作不输出原始文件
- 用于操作原始内存的正确数据类型
- 如何从原始数组到std::vector执行memcpy等效操作
- c++操作结构体的原始数据
- 如果对赋给指针的迭代器进行自增操作,该指针是否保留原始内存位置?
- 当对任何数字进行移位操作时,如何返回原始数字
- 矩阵乘以矢量操作与原始缓冲区在本征
- 自动生成移动操作和原始指针成员