C ++在模板声明中使用默认值

用户名

我有以下代码...

#include <iostream>

using namespace std;

template<typename R, R V = R()> R X() { return V; }

int main()
{
    cout << boolalpha << X<bool>() << endl;    
    cout << boolalpha << X<bool, true>() << endl;

    cout << X<int>() << endl;
    cout << X<int, 5>() << endl;

    cout << X<void>() << endl;   // compiler error

    return 0;
}

...适用于bool和int情况,但不适用于void情况。有办法解决吗?

我知道这样的代码是可以接受的...

void F()
{
    return void();
}

...因此需要以某种方式使该行为脱离模板。

曼卡瑟

使用std :: enable_if在两个功能模板之间进行选择。现场示例

#include <iostream>
#include <type_traits>
using namespace std;

template<typename R, R V = R()>
typename std::enable_if<!is_same<R, void>::value, R>::type X() { return V; }

template<typename R>
typename std::enable_if<is_same<R, void>::value, R>::type X() { return; }

int main()
{
    cout << boolalpha << X<bool>() << endl;    
    cout << boolalpha << X<bool, true>() << endl;

    cout << X<int>() << endl;
    cout << X<int, 5>() << endl;

    X<void>(); // You can't print `void` with standard iostreams...

    return 0;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

在C#方法重载中使用默认值

来自分类Dev

C ++默认值

来自分类Dev

在类C ++中使用构造函数为char数组提供默认值

来自分类Dev

c# - 在c#中使用XMLSerializer序列化时如何包含具有默认值的属性

来自分类Dev

使用cin的C ++中变量的默认值>>

来自分类Dev

C#可枚举。使用默认值

来自分类Dev

在C#中使用默认通用值

来自分类Dev

在C#中使用默认通用值

来自分类Dev

在C ++中使用声明

来自分类Dev

C#Convert.ToBoolean的默认值

来自分类Dev

在C#中设置默认值

来自分类Dev

C#结构默认值

来自分类Dev

struct c中的默认值[重复]

来自分类Dev

C ++中类成员的默认值

来自分类Dev

在C#中设置默认值

来自分类Dev

turbo c 中的默认值

来自分类Dev

当我们在C ++中使用像默认值作为参数的函数之类的变量时,这意味着什么?

来自分类Dev

了解如何声明模板参数的默认值

来自分类Dev

在C ++中使用模板

来自分类Dev

使用C ++和map / unordered_map创建直方图:不存在的键的默认值

来自分类Dev

函数参数默认值std:vector是否使用Rcpp和C ++ 11初始化?

来自分类Dev

在C中的结构上使用malloc之后,数组中的默认值是多少

来自分类Dev

使用c:forEach标记时,在选择框中选择默认值

来自分类Dev

C ++使用默认值实例化Struct内部的2D矢量

来自分类Dev

在模板方法参数中使用Ruby常量作为默认值?

来自分类Dev

C / C ++中的静态指针默认值

来自分类Dev

在C ++中使用带有默认模板参数的模板类时出现“模板参数过多错误”

来自分类Dev

在C ++中使用奇怪的声明

来自分类Dev

使用`std :: vector`作为模板模板参数的默认值