使用 sfinae:
#include <type_traits>
template <typename Functor, typename... Args>
auto Decorate(Functor f, Args&&... args)
-> typename std::enable_if<std::is_same<decltype(f(std::forward<Args>(args)...)), void>::value, void>::type
{
// preconditions
f(std::forward<Args>(args)...);
// postconditions
return;
}
template <typename Functor, typename... Args>
auto Decorate(Functor f, Args&&... args)
-> typename std::enable_if<!std::is_same<decltype(f(std::forward<Args>(args)...)), void>::value, decltype(f(std::forward<Args>(args)...))>::type
{
// preconditions
auto result = f(std::forward<Args>(args)...);
// postconditions
return result;
}
测试:
void f(int x) {
std::cout << "f(" << x << ")" << std::endl;
return;
}
int g(int x) {
std::cout << "g(" << x << ")" << std::endl;
return x * x;
}
int main()
{
Decorate(f, 3);
std::cout << Decorate(g, 3);
return 0;
}
f(3)
g(3)
9