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

c – enable_if添加具有默认参数的函数参数?

发布时间:2020-12-16 05:31:47 所属栏目:百科 来源:网络整理
导读:我无法理解 here提出的第二个场景.它说: ?Scenario 2: Adding a function parameter that has a default argument: template your_stuff your_return_type_if_presentyourfunction(args,enable_if_tyour condition,FOO = BAR) { // ...} Scenario 2 leaves
我无法理解 here提出的第二个场景.它说:

?Scenario 2: Adding a function parameter that has a default argument:

template <your_stuff> your_return_type_if_present
yourfunction(args,enable_if_t<your condition,FOO> = BAR) {
    // ...
}

Scenario 2 leaves the parameter unnamed. You could say ::type Dummy = BAR,but the name Dummy is irrelevant,and giving it a name is likely to trigger an unreferenced parameter warning. You have to choose a FOO function parameter type and BAR default argument. You could say int and 0,but then users of your code could accidentally pass to the function an extra integer that would be ignored. Instead,we recommend that you use void ** and either 0 or nullptr because almost nothing is convertible to void **:

template <your_stuff> your_return_type_if_present 
yourfunction(args,typename enable_if<your_condition,void **>::type=nullptr) {
 // ...
}

如果方案2使参数未命名,那么它可以使用什么?
有没有办法让这样的代码与enable_if一起工作?

enum otype {oadd,omull};
template<otype o>
int add(int num1,std::enable_if<o == oadd,int>::type int= num2)
{
    if (o == omull) return num1 * num1;
    if (o == oadd ) return num1 + num2;
 }

解决方法

enable_if示例(如果有帮助):

对于具有非void返回类型的函数:

对于单一条件:

template <template T,typename std::enable_if<!std::is_same<T,std::string>::value>::type* = nullptr >
T func(T x){}

对于多种情况:

template <template T,std::string>::value &&!std::is_same<T,int>::value>::type* = nullptr >
T func(T x){}

对于具有void返回类型的函数:

对于单一条件:

template <template T>
typename std::enable_if<!std::is_same<T,std::string>::value>::type
func(T x){}

对于多种情况:

template <template T>
typename std::enable_if<!std::is_same<T,int>::value>::type
func(T x){}

不要忘记包含#include< type_traits>

(编辑:李大同)

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

    推荐文章
      热点阅读