【发布时间】:2017-12-22 03:29:12
【问题描述】:
我希望一个类有两种不同的push 实现,并根据布尔模板参数进行选择。我尝试使用this answer 中描述的 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”的错误,我不明白为什么。虽然我的代码与链接答案中的代码不完全相同,但看起来非常相似,我无法发现关键区别。
我也尝试使用类似于this answer 中建议的语法,但它也不起作用(错误是“无法重新声明类成员”):
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 */ }
我怎样才能做到这一点?
【问题讨论】: