如何使用布尔模板参数启用成员函数?
How to enable member function using boolean template parameter?
我希望一个类有两个不同的push
实现,并根据布尔模板参数进行选择。我尝试使用本答案中所述的 SFINAE 原理,如下所示:
template<class T, bool foo=true>
class Bar {
template <>
typename std::enable_if<foo>::type
push(const T& value) { /* one implementation */}
template <>
typename std::enable_if<!foo>::type
push(const T& value) { /* another implementation */ }
}
但是,我在 gcc 下收到"无法专门化类范围内的函数push
"的错误,我不明白为什么。虽然我的代码与链接答案中的代码不完全相同,但它看起来非常相似,我无法发现关键差异。
我还尝试使用类似于此答案中建议的语法,但它也不起作用(错误是"无法重新声明类成员"):
template <bool enable=foo>
typename std::enable_if<enable>::type
push(const T& value) { /* one implementation */}
template <bool enable=!foo>
typename std::enable_if<enable>::type
push(const T& value) { /* another implementation */ }
我怎样才能做到这一点?
首先,SFINAE 使用函数模板重载; 所以你应该使用第二种方法。但是您声明了两个具有相同签名的重载;请注意,模板参数的默认参数不属于签名。
将其更改为
template <bool enable=foo>
typename std::enable_if<enable>::type
// ~~~~~~
push(const T& value) { /* one implementation */}
template <bool enable=foo>
typename std::enable_if<!enable>::type
// ~~~~~~~
push(const T& value) { /* another implementation */ }
作为替代方案:
-
C++17
if constexpr
:template<class T, bool foo=true> class Bar { public: void push(const T& value) { if constexpr(foo) { /* one implementation */ } else { /* another implementation */ } } };
-
标签调度:
template<class T, bool foo=true> class Bar { void push_impl(const T& value, std::true_type) { /* one implementation */ } void push_impl(const T& value, std::false_type) { /* another implementation */ } public: void push(const T& value) { push_impl(value, std::integral_constant<bool, foo>{}); } };
相关文章:
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 将公共但非静态的成员函数与ALGLIB集成
- 使用指向成员的指针将成员函数作为参数传递
- 将重载的成员函数传递给函数模板
- 我不小心调用了一个没有自己类对象的成员函数.但这是怎么回事呢
- 如何在C++中使用非静态成员函数作为回调函数
- C++错误C2600:无法定义编译器生成的特殊成员函数(必须首先在类中声明)
- 关联容器的下界复杂性:成员函数与非成员函数
- 在 C++ 中用派生类型重写成员函数
- 链表的泛型函数remove()与成员函数remove)
- 如何将lambda作为模板类的成员函数参数
- constexpr构造函数需要常量成员函数时出现问题
- 将自由函数绑定为类成员函数
- 区分非成员函数和头文件中的成员函数
- 如何从子成员函数修改父公共成员变量
- 保留对其他类的成员函数的引用
- 在运算符重载定义中使用成员函数(const错误)
- 内联如何影响模块接口中的成员函数
- 将成员函数指针作为参数传递给模板方法