c++ 03检查模板参数是否为空
C++03 check if template parameter is void?
考虑一个函数
template <typename Ret>
Ret function(...) {
Ret a;
// . . . do something with a
return a;
}
如果我把它命名为
function<void>();
编译器说
错误:变量或字段'a'声明为空
错误:return语句带值,函数返回'void' [-fpermissive]
如何在这个函数中强制检查,例如
template <typename Ret>
Ret function(...) {
// if (Ret is void) return;
Ret a;
// . . . do something with a
return a;
}
我知道c++ 11有std::is_void
和std::is_same
bool same = std::is_same<Ret, void>::value;
c++ 03里有什么吗?
您可以专门化,或者编写自己的is_same
,这很容易,当然您也可以使用非标准库(例如boost)。
template<typename Ret>
Ret function(...)
{
Ret a;
// ...
return a;
}
template<>
void function<void>(...)
{
}
的
template<typename T, typename U>
struct is_same
{
static const bool value = false;
};
template<typename T>
struct is_same<T, T>
{
static const bool value = true;
};
顺便说一句,is_same
并不像你想的那么简单。您还需要专门化或重载
template<typename Ret>
typename enable_if<!is_same<Ret, void>::value, Ret>::type
function(...)
{
Ret a;
// ...
return a;
}
template<typename Ret>
typename enable_if<is_same<Ret, void>::value, Ret>::type
function(...)
{
}
运行时if
是不够的,模板的所有实例化必须是可编译的。在你的情况下,专业化可能是最好的做法:
template <typename Ret>
Ret function(...) {
Ret a;
// . . . do something with a
return a;
}
template <>
void function<void>(...) {
return;
}
同时,boost::is_same
可用于c++ 03。
相关文章:
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 是否可以对零模板参数进行模板专门化
- 函数作为模板参数,是否对返回类型强制约束
- visual是否可以在c++中创建一个接收无限数量相同类型(或至少相当数量)参数的函数
- 函数是否可以访问传递给main()的参数
- 在C++中,使用带有 std::optional 参数的函数<T>来表示可选参数是否有意义?
- 如何检查给定的参数是否为 cv::noArray()?
- 表达式 SFINAE:如何根据类型是否包含具有一个或多个参数的函数来选择模板版本
- 如果返回 -1,时间() 的参数是否被修改?
- 用于检查值是否为其任何参数的帮助程序函数
- 将类型声明为类型模板参数的模板参数的一部分是否合法?
- 模板化检查是否存在带有参数列表的类成员函数?
- 我如何知道作为参数的size_t在函数中是否有效?
- 是否可以在C++中有一个"generic"模板参数,该参数可以是非类型模板参数或类型?
- 是否可以就地构造一个固定大小的数组作为函数参数?
- C++方法是否可以根据传递给构造函数的参数具有不同的返回类型?
- 是否可以在运行时强制转换模板参数?
- 是否可以在不填充自己的参数的情况下将模板函数作为参数传递?
- 编译器是否强制根据模板参数计算表达式?
- C++中大多数/所有 setter 函数的参数是否应该写为常量引用?