简体   繁体   English

C++,重载函数,模板

[英]C++, overloding functions, templates

I want to ask is it possible to write overloaded function for arithmetic's type which returns double and for containers (array, vector, valarray, etc...) which returns valarray.我想问一下是否可以为返回双精度的算术类型和返回 valarray 的容器(数组、向量、valarray 等)编写重载函数。 Simple example简单的例子

template<typename T> 
double foo(T x) { 
  return x; 
}
 
template<typename T> 
std::valarray<double> foo(T const &arr) {
  std::valarray<double> valarr(1,1); 
  return valarr; 
}

In result I get expected message: call to 'foo' is ambiguous.结果我得到了预期的消息:对 'foo' 的调用是不明确的。 Is there any possibility to write such a functions?有没有可能写出这样的函数?

I would really appreciate all comments.我真的很感激所有的评论。

You can use C++20 concepts :您可以使用 C++20概念

#include <valarray>
#include <concepts>

template<typename T> 
  requires std::is_arithmetic_v<T>
double foo(T x) { 
  return x; 
}

template<std::ranges::random_access_range T>
  requires std::is_arithmetic_v<std::ranges::range_value_t<T>>
std::valarray<double> 
foo(T const& arr) {
  std::valarray<double> valarr(1,1); 
  return valarr; 
}

Demo.演示。

For C-array types, it would be:对于 C 数组类型,它将是:

template<typename T, std::size_t N>
std::valarray<double> foo(T const (&arr)[N])
{
    // ...
}

Demo演示

You can use std::enable_if to do what you want as follows:您可以使用std::enable_if执行您想要的操作,如下所示:

#include <iostream>
#include <string>
#include <valarray>

//overload for arthemtic types
template<typename T>
std::enable_if_t<std::is_arithmetic_v<T>, double> foo(T x)
{
    std::cout<<"arithmetic version"<<std::endl;
    return x;
}
//overload for array
template<typename T, std::size_t N>
std::valarray<double> foo(T const (&arr)[N])
{
    std::valarray<double> valarr(2,5); 
    std::cout<<"array version"<<std::endl;
    return valarr;
}

//overload for non-arthemtic types
template<typename T>
std::enable_if_t<!std::is_arithmetic_v<T>, T> foo(T x) //note the "!" in this version
{
    std::cout<<"non-arithmetic version"<<std::endl;
    return x;
}
int main() {
  int arr[3] = {1,2,3};
    foo(arr);//uses array version
    foo(5); //uses arithmetic version
    int p= 0, *c = &p;
    
    foo("string");//uses array version
    foo(p);//uses arithmetic version
    foo(c); //uses non-arithmetic version
} 

The output of the above program can be seen here .上面程序的输出可以在这里看到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM