加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

模板化C函数,第一个参数设置为第二个参数作为默认参数

发布时间:2020-12-16 09:22:59 所属栏目:百科 来源:网络整理
导读:我有这样的功能: template typename A,typename Bvoid foo(const B b){ ...} A应该是可选的;如果没有在函数调用中明确定义,则应将其设置为B.目的是避免不必要的详细代码: int i;// First variant: A is specified explicitlyfoofloat(i);// Second variant
我有这样的功能:

template <typename A,typename B>
void foo(const B & b)
{
    ...
}

A应该是可选的;如果没有在函数调用中明确定义,则应将其设置为B.目的是避免不必要的详细代码:

int i;

// First variant: A is specified explicitly
foo<float>(i);

// Second variant: A is set to B implicitly
// This is because foo < int > (i) is unnecessarily verbose
foo(i);

但是,我还没有办法做到这一点.任何人都能想出一个吗?

解决方法

#include <type_traits>

struct deduce_tag;

template <typename PreA = deduce_tag,typename B>
void foo(const B & b) {
    using A = std::conditional_t<
        std::is_same<PreA,deduce_tag>::value,B,PreA
    >;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读