简写函数模板(abbreviated function template):当占位符类型(auto或concept auto)出现在函数声明或函数模板声明的参数列表中时,该声明将声明一个函数模板,并且每个占位符的一个虚构模板参数(one invented template parameter)将附加到模板参数列表。如下所示:简写函数模板只是指定函数模板的一种简便方法

void f1(auto); // same as template<class T> void f1(T)
void f2(C1 auto); // same as template<C1 T> void f2(T), if C1 is a concept
void f3(C2 auto...); // same as template<C2... Ts> void f3(Ts...), if C2 is a concept
void f4(const C3 auto*, C4 auto&); // same as template<C3 T, C4 U> void f4(const T*, U&);

template<class T, C U>
void g(T x, U y, C auto z); // same as template<class T, C U, C W> void g(T x, U y, W z);

template<>
void f4<int>(const int*, const double&); // specialization of f4<int, const double>

      以下为测试代码:

namespace {

//template<typename T>
//T get_sum(T a, T b)
auto get_sum(auto a, auto b) // 不受约束的auto
{
    return (a + b);
}

template <typename T>
concept C = std::is_integral_v<T> || std::is_floating_point_v<T>;

auto get_sum2(C auto a, C auto b) // 受约束的auto
{
    return (a + b);
}

} // namespace

int test_abbreviated_function_template()
{
    std::cout << "sum: " << get_sum(6, 8) << std::endl;
    std::cout << "sum: " << get_sum(6, 8.8) << std::endl;
    std::cout << "sum: " << get_sum(std::string("hello"), std::string(", world")) << std::endl;

    std::cout << "sum2: " << get_sum2(6, 8) << std::endl;
    std::cout << "sum2: " << get_sum2(6, 8.8) << std::endl;
    //std::cout << "sum2: " << get_sum2(std::string("hello"), std::string(", world")) << std::endl; // // error C2672: "get_sum2":未找到匹配的重载函数

    return 0;
}

      执行结果如下图所示:

      GitHubhttps://github.com/fengbingchun/Messy_Test

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部