我正在尝试扩展和专门化来自 rapidCheck 的 BitStream 类的成员函数。
template <typename Source>
class BitStream {
public:
explicit BitStream(Source source);
/// Returns the next value of the given type with maximum size.
template <typename T>
constexpr T next();
constexpr char next();
};
template <typename Source>
BitStream<Source>::BitStream(Source source)
{}
template <typename Source>
template <typename T>
constexpr T BitStream<Source>::next() {
return T();
}
template <typename Source>
constexpr char BitStream<Source>::next() { return (char)(1); }
int main() {
BitStream<int> bs(2);
static_assert( bs.next<int>() == 0 ); // as expected
static_assert( bs.next() == 1 ); // not really a specialization
static_assert( bs.next<char>() == 1 ); // fails, but this should succeed!
}
这个简化的代码片段可以编译,但最后一个断言失败,因为我无法真正将
next()
专门化为 T=char
。如何才能实现这一目标呢?
我这里的要求是我想与rapidcheck的其余部分兼容,所以bs.next<char>()
应该调用专门的版本。
预先感谢!
您只能在专门的类模板中专门化成员模板,如以下简化示例所示:
template <typename Source>
class BitStream {
public:
explicit BitStream(Source source);
/// Returns the next value of the given type with maximum size.
template <typename T>
constexpr T next();
};
template <>
template <>
constexpr char BitStream<int>::next<char>() {
return 1;
}
int main() {
BitStream<int> bs(2);
static_assert( bs.next<char>() == 1 ); // succeed
}