C ++ 03检查模板参数是否为void? [英] C++03 check if template parameter is void?
问题描述
考虑一个函数
template< typename Ret>
Ret函数(...){
Ret a;
//。 。 。用
返回一个;
}
如果我将其称为
function< void>();
编译器说
错误:变量或字段'a'声明为无效
错误:返回语句带有一个值,返回'void' p>
如何在此函数中强制执行检查,例如
template< typename Ret>
Ret函数(...){
// if(Ret is void)return;
Ret a;
//。 。 。用
返回一个;
}
我知道C ++ 11有 std :: is_void
和 std :: is_same
bool same = std :: is_same< Ret,void> :: value;
C ++ 03中的任何内容?提前感谢。
您可以专门设计,或撰写您自己的 is_same
,这很容易,或者当然可以使用非标准库(例如boost)。
专业化
模板< typename Ret>
Ret函数(...)
{
Ret a;
// ...
return a;
}
模板<>
void function< void>(...)
{
}
自己
模板< 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;
};
BTW is_same
你认为。您还需要专门化或重载
模板< 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(...)
{
}
因此,专业化更简单。
Consider a function
template <typename Ret> Ret function(...) { Ret a; // . . . do something with a return a; }
If I call this as
function<void>();
the compiler says
error: variable or field 'a' declared void
error: return-statement with a value, in function returning 'void' [-fpermissive]
How do I enforce a check on in this function, for instance
template <typename Ret> Ret function(...) { // if (Ret is void) return; Ret a; // . . . do something with a return a; }
I know C++11 has
std::is_void
andstd::is_same
bool same = std::is_same<Ret, void>::value;
Anything in C++03 ? Thanks in advance.
解决方案You can just specialize, or write your own
is_same
, that's pretty easy, or of course you can use not-standard libraries (for example boost).Specialization
template<typename Ret> Ret function(...) { Ret a; // ... return a; } template<> void function<void>(...) { }
Own
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; };
BTW with
is_same
it's not so simple, that you think. You also need specialization, or overloadingtemplate<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(...) { }
So, just specialization is more simple.
这篇关于C ++ 03检查模板参数是否为void?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!