我正在尝试编写一个函数,该函数允许针对各种不同类型的向量应用各种Boost累加器对象。
对于某些类型,累加器对象没有意义。例如,如果传入bool
类型的数组,则大多数累加器将无法工作。
简化了我的代码:
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/count.hpp>
using namespace boost::accumulators;
template<class V, class T> static void _apply(T* ptr, size_t n) {
accumulator_set<T, features<V> > acc;
std::for_each(ptr, ptr + n, std::ref(acc));
};
int main() {
bool v[] = { true, false, true };
_apply<tag::count, bool>(v, 3);
}
我试图弄清楚如何使用SFINAE提供运行时错误消息_apply
,该错误消息的类型没有意义,而不是编译器错误。
error: no match for ‘operator+=’ (operand types are ‘const std::_Bit_reference’ and ‘const bool’)
答案 0 :(得分:0)
您可能正在寻找模板专业化。遵循以下原则:
namespace internal {
template<typename V, typename T>
struct ApplyHelper {
static void apply(T* ptr, size_t n) { /* general implementation here */ }
};
template<typename V>
struct ApplyHelper<V, bool> {
static void apply(bool* ptr, size_t n) { /* report error here */ }
};
}
template<typename V, typename T>
static void _apply(T* ptr, size_t n) {
internal::ApplyHelper<V, T>::apply(ptr, n);
};