C++在模板声明中使用默认值
C++ using default values in template declaration
我有以下代码。。。
#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;
}
您可以创建一个无效类型(None)并指定具有类型特征的返回类型:
#include <iostream>
struct None {};
// It may not be reasonable o provide the operator:
inline std::ostream& operator << (std::ostream& stream, None) {
return stream;
}
template<typename R>
struct Traits {
typedef R return_type;
};
template<>
struct Traits<void> {
typedef None return_type;
};
template<typename R>
typename Traits<R>::return_type X() { return typename Traits<R>::return_type(); }
template<typename R, typename Traits<R>::return_type V>
typename Traits<R>::return_type X() { return V; }
int main()
{
std::cout << std::boolalpha << X<bool>() << std::endl;
std::cout << std::boolalpha << X<bool, true>() << std::endl;
std::cout << X<int>() << std::endl;
std::cout << X<int, 5>() << std::endl;
std::cout << X<void>() << std::endl;
return 0;
}
此外,函数X
被一分为二,以避免默认模板参数的问题。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 具有默认值的引用获取函数
- 当给定默认值时,为什么此模板参数推导失败
- 从具有默认值的部分指定模板类继承时发生SWIG错误,具有不带默认值的正向声明
- 格式化浮点值:返回默认值
- 如何将数组部分初始化为某个默认值?
- asn1c 不会从 asn.1 模块中提取八位字节字符串的默认值
- 创建一个包含 c++ 默认值的环境文件
- C++(和 ROS) - 包含与前向声明引用,设置默认值和类型定义
- Makefile g++ 使用命令行中的 -D 变量进行编译,默认值
- Switch 语句(字符串)一直选择默认值,除非其为零
- 如何使用默认值将枚举声明为 extern
- 如何在提升程序选项中设置矢量<矢量>的默认值<string>
- 正向声明的枚举,默认值以.h为单位
- 在C 中声明具有默认值的大型数组
- 了解如何声明模板参数的默认值
- 基本成员初始化与在类声明中指定默认值
- 需要声明析构函数为默认值
- C++在模板声明中使用默认值
- 在类中声明的枚举的默认值