【发布时间】:2017-12-19 15:51:52
【问题描述】:
我有类似以下的内容:
template <typename T>
struct Base {
auto func() {
// do stuff
auto x = static_cast<T&>(*this).func_impl();
// do stuff
return x;
}
};
struct A : Base<A> {
int func_impl() {
return 0;
}
};
struct B : Base<B> {
void func_impl() {
}
};
int main() {
A a;
int i = a.func();
B b;
b.func();
return 0;
}
问题是我无法将派生类中func_impl 的返回类型声明为void,如B 所示。我尝试像这样使用 SFINAE 解决问题:
template <typename T>
struct Base {
template <typename = enable_if_t<!is_void<decltype(declval<T>().func_impl())>::value>>
auto func() {
// do stuff
auto x = static_cast<T&>(*this).func_impl();
// do stuff
return x;
}
template <typename = enable_if_t<is_void<decltype(declval<T>().func_impl())>::value>>
void func() {
// do stuff
static_cast<T&>(*this).func_impl();
// do stuff
}
};
但是编译器给出了错误:invalid use of incomplete type 'struct A' 和 invalid use of incomplete type 'struct B'。
有没有办法实现我想要的?
【问题讨论】:
-
Works here. 为什么你认为不能将
func_impl的返回类型声明为void? -
你是对的。谢谢!实际上我在
func_impl-call 之后也做了一些事情,所以我必须将值保存到一个变量中并在之后返回它。我现在改了问题。
标签: c++ templates c++14 sfinae