如何使用布尔模板参数启用成员函数? [英] How to enable member function using boolean template parameter?

查看:43
本文介绍了如何使用布尔模板参数启用成员函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望一个类具有两种不同的 push 实现,并根据布尔模板参数进行选择.我尝试使用 this answer 中所述的 SFINAE 原则,如下所示:

I would like a class to have two different implementations of push, and choose based on a boolean template argument. I tried using the SFINAE principle as described in this answer, like so:

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"的错误,我不明白为什么.虽然我的代码与链接答案中的不完全一样,但它似乎非常相似,我无法发现关键区别.

however, I am getting an error of "cannot specialize a function push within class scope" under gcc, and I do not understand why. Although my code is not exactly like that in the linked answer, it seems very similar and I can't spot the critical difference.

我也尝试使用类似于这个答案中建议的语法,但它也不起作用(错误是不能重新声明类成员"):

I also tried using a syntax similar to that suggested in this answer but it is also not working (the error is "class member cannot be redeclared" instead):

  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 */ } 

我怎样才能做到这一点?

How can I accomplish this?

推荐答案

首先,SFINAE 与函数模板重载一起使用;所以你应该采用第二种方法.但是你声明了两个具有相同签名的重载;注意模板参数的默认参数不属于签名.

Firstly, SFINAE works with function templates overloading; so you should go with the 2nd approach. But you declare two overloads with same signature; note that the default argument of template parameter doesn't belong to the signature.

改成

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 */ } 

这篇关于如何使用布尔模板参数启用成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆