C ++ 03 check if a template parameter is not?
Consider the function
template <typename Ret>
Ret function(...) {
Ret a;
// . . . do something with a
return a;
}
If I call it like
function<void>();
the compiler says
error: variable or field 'a' declared void
error: return-statement with value, in function returning 'void' [-fpermissive]
How to enable validation in this function like
template <typename Ret>
Ret function(...) {
// if (Ret is void) return;
Ret a;
// . . . do something with a
return a;
}
I know that C ++ 11 has std::is_void
andstd::is_same
bool same = std::is_same<Ret, void>::value;
Anything in C ++ 03? Thanks in advance.
source to share
You can just specialize or write your own is_same
, which is pretty easy, or of course you can use non-standard libraries (like boost).
specializations
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;
};
By the way, is_same
it's not as easy as you think. You also need specialization or overload
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(...)
{
}
So, it's just that specialization is easier.
source to share
The execution time if
will not be sufficient, all instances of the template must be compiled. In your case, specialization might be the best way:
template <typename Ret>
Ret function(...) {
Ret a;
// . . . do something with a
return a;
}
template <>
void function<void>(...) {
return;
}
Also available for C ++ 03 boost::is_same
.
source to share