Is there any way to achieve the specified behaviour? If there is some trick or this could be done using traits or enable_if
, please let me know.
template <typename T> struct Functional {
T operator()() const {
T a(5);
// I want this statement to be tranformed into
// plain 'return;' in case T = void
return a; // <---
}
};
int main() {
Functional<int> a;
a();
Functional<void> b;
b(); // <--- Compilation error here
}
Just specialize for void:
template <typename T> struct Functional {
T operator()() const {
T a(5);
return a;
}
};
template <> struct Functional<void> {
void operator()() const {
}
};
Just say the following. It works perfectly well with T
being void
and is equivalent to the code you have shown
T operator()() const {
return static_cast<T>(5);
}
you could use a specialization
template <> struct Functional<void> {
void operator()() const {
}
};
This should work
template <> struct Functional<void> //specialized for 'void'
{
void operator()() const {
//do something
return ; //optional
}
};
EDIT:
You can also write (Simpler approach)
T operator()() const {
return T(5); // static_cast<> not even required
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With