gpt4 book ai didi

c++ - 使用enable_if根据模板类型隐藏成员函数

转载 作者:行者123 更新时间:2023-12-03 08:14:10 25 4
gpt4 key购买 nike

如果模板参数与特定类型匹配,我希望我的类模板提供额外的函数成员。我正在尝试使用 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 不能隐式转换为 时可用>值类型。我将如何实现这个?

最佳答案

要应用 SFINAE,您需要尝试使用 SFINAE 的对象拥有自己的模板参数,并且需要在条件中使用该模板参数。在这种情况下,您可以通过将模板参数 typename V = value_type 添加到模板参数并使用 V 而不是 value_type 来修复此问题。现在条件将取决于 V,它是成员函数的模板参数:

#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 V = value_type, typename = typename std::enable_if< !std::is_convertible< other_type, V >::value >::type >
// added ^^^^^^^^^^^^^^^^^^^^^^^^ changed value_type to V ^
void function(const other_type& val) {};

// overload #2
// error: no type named ‘type’ in ‘struct std::enable_if<false, void>’
template < typename V = value_type, std::enable_if_t< !std::is_convertible< other_type, V >::value >* = nullptr >
// added ^^^^^^^^^^^^^^^^^^^^^^^^ changed value_type to V ^
void function(const other_type& val) {};
};



int main(int argc, char const *argv[]) {
myClass< std::string > foo; // OK
myClass< float > bar; // OK

return 0;
}

关于c++ - 使用enable_if根据模板类型隐藏成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69975364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com