【发布时间】:2019-08-04 09:31:02
【问题描述】:
#include <type_traits>
class Base {
public:
virtual bool f() {
return true;
}
};
template<typename T>
class Derived : public Base {
std::enable_if_t< std::is_copy_constructible<T>::value, bool > f() override {
return true;
}
std::enable_if_t< !std::is_copy_constructible<T>::value, bool > f() override {
return false;
}
};
以上代码无法编译。由于某种原因,我无法理解,编译器将这两个函数视为相同的重载,然后再被 SFINAE 删除。
然而,我不明白我该如何解决这个问题。我找到的文档state 我应该在函数上使用模板。但是,这不起作用,因为该函数是虚拟的。
我尝试通过调用非虚拟函数来解决问题,但我也无法编译:
template<typename T>
class Derived : public Base {
virtual bool f() override {
return f_impl();
}
private:
template< std::enable_if_t< std::is_copy_constructible<T>::value > = 0 >
bool f_impl() {
return true;
}
template< std::enable_if_t< !std::is_copy_constructible<T>::value > >
bool f_impl() {
return false;
}
};
int main() {
Derived<int> a;
std::cout<<a.f()<<"\n";
}
编译失败:
so.cpp: In instantiation of ‘class Derived<int>’:
so.cpp:29:18: required from here
so.cpp:18:10: error: ‘std::enable_if<true, void>::type’ {aka ‘void’} is not a valid type for a template non-type parameter
我显然在这里做错了什么,但我不知道什么是正确的方法。
【问题讨论】:
-
为什么不直接返回一个值
bool f() override { return std::is_copy_constructible<T>::value; }? -
因为这是一个简化的例子。实际上,我需要做两件截然不同的事情。
标签: c++ templates template-meta-programming sfinae enable-if