#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; }
? - user7860670