Sha*_*esh 5 c++ templates sfinae enable-if template-meta-programming
#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;
}
};
Run Code Online (Sandbox Code Playgroud)
上面的代码不能编译。由于某种原因我没能理解,编译器在 SFINAE 删除一个函数之前将这两个函数视为相同的重载。
然而,我不明白的是我如何解决这个问题。我发现的文档指出我应该在函数上使用模板。但是,这不起作用,因为该函数是虚拟的。
我尝试通过调用非虚拟函数来卸载问题,但我也无法编译:
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";
}
Run Code Online (Sandbox Code Playgroud)
编译失败:
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
Run Code Online (Sandbox Code Playgroud)
我显然在这里做错了什么,但我不知道什么是正确的方法。
不幸的是,你不能这样做。SFINAE使用模板;例如,从您的第二个示例作品修订的以下代码。
template< typename X = T>
std::enable_if_t< std::is_copy_constructible<X>::value, bool >
f_impl() {
return true;
}
template< typename X = T>
std::enable_if_t< !std::is_copy_constructible<X>::value, bool >
f_impl() {
return false;
}
Run Code Online (Sandbox Code Playgroud)
但是virtual函数不能是模板,仅此而已。