【发布时间】:2021-12-26 17:12:44
【问题描述】:
如果模板参数匹配特定类型,我希望我的类模板提供额外的函数成员。我正在尝试使用 std::enable_if 来获得 SFINAE 实现,但我正在努力为此找到正确的语法。对于类似的问题,我尝试了几种解决方案,但由于某种原因,它们都无法编译。
#include <type_traits>
#include <string>
template < typename T >
class myClass {
public:
using value_type = T;
using other_type = int;
myClass() = default;
virtual ~myClass() = default;
// 'default' member
void function(const value_type& val) {};
// overload #1
// error: no type named ‘type’ in ‘struct std::enable_if<false, void>’
template < typename = typename std::enable_if< !std::is_convertible< other_type, value_type >::value >::type >
void function(const other_type& val) {};
// overload #2
// error: no type named ‘type’ in ‘struct std::enable_if<false, void>’
template < std::enable_if_t< !std::is_convertible< other_type, value_type >::value >* = nullptr >
void function(const other_type& val) {};
};
int main(int argc, char const *argv[]) {
myClass< std::string > foo; // OK
myClass< float > bar; // error: no type named ‘type’ in ‘struct std::enable_if<false, void>’
return 0;
}
我希望function 可用于所有类型,但它的重载仅在other_type 不能隐式转换为value_type 时可用。我将如何实施?
【问题讨论】:
-
您可以访问 C++20 吗?
requires(!std::is_convertible<other_type, value_type >::value)会解决这个问题。
标签: c++ templates sfinae typetraits