有没有办法实现指定的行为?如果有一些技巧或者可以使用特征来完成enable_if
,请告诉我.
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
}
Run Code Online (Sandbox Code Playgroud)
Dav*_*eas 24
只是专注于虚空:
template <typename T> struct Functional {
T operator()() const {
T a(5);
return a;
}
};
template <> struct Functional<void> {
void operator()() const {
}
};
Run Code Online (Sandbox Code Playgroud)
Joh*_*itb 10
只需说以下内容即可.它非常适合T
存在void
并且相当于您显示的代码
T operator()() const {
return static_cast<T>(5);
}
Run Code Online (Sandbox Code Playgroud)