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

标签 c++ templates

我有以下代码...

#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在两个功能模板之间进行选择。 Live Example :

#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;
}

关于C++ 在模板声明中使用默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23169520/

相关文章:

C++函数中的广义二维数组

c++如何用多个字符填充空宽度?

c++ - MemoryDC占用内存还是显卡内存?

c++ - 编译时单例多次实例化检测

c++ - 不同的默认按钮设计行为

c++ - 是否必须让默认构造函数在 C++ 中使用统一初始化

email - Magento电子邮件模板If语句

c++ - 使用面向对象的 C 库

python - 在 Django 应用程序中提供静态网页的最佳方式是什么?

c++ - 在 C++ 计算器中使用模板