我想要什么语法实现对用户侧:默认参数
double a(1.), b(2.), deps(.1);
bool res1 = compare<double>()(a, b); // works with default eps
bool res2 = compare<double, &deps>()(a, b); // works with explicitly provided eps
float c(1.), d(1.). feps(.1);
bool res3 = compare<float>()(c, d); // don't have default eps - must not compile
bool res4 = compare<float, &feps>()(c, d); // works only with provided eps
我现在(不工作,因为偏特默认参数是不允许的)有哪些实现了这一点:
extern double eps_double; // somewhere defined and initialized
template<typename T, const T* eps>
struct compare { // actually inherits std::binary_function
bool operator()(const T& t1, const T& t2) {
return t1 < t2 - *eps;
}
};
template<const double* eps = &eps_double>
struct compare<double, eps> { // the same as in default implementation
};
我试着用enable_if和包装类有静态成员,但静态成员不能被分配给extern变量;
更新: 实际的问题是一般结构和专用结构的名称相等。我不知道如何度过,即使没有重命名工作:
// treats all explicitly passed eps and don't need default parameter
template<typename T, const T* eps>
struct compare_eps { // need another name!
bool operator()(const T& t1, const T& t2) {
return t1 < t2 - *eps;
}
};
// don't need default parameter either
// because we always know what eps to use for a concrete type
template<typename T>
struct compare {
// define nothing -> will not compile on types we don't have specialization for
};
template<>
struct compare<double> {
// use here eps_double hardcoded
};
对不起,这是一个错字,正确的版本是'compare()(a,b);'粗略。请参阅我的问题更新。 –
Riga
2011-04-14 11:41:48
@Johannes,你在最后一段中的含义是什么“如果你只提供,默认参数也会被使用,但是不起作用”? –
Nim
2011-04-14 12:12:20
@litb我无法使用最后一种方法的原因是我的专业化不仅适用于双层,而且还适用于其他类型。 – Riga 2011-04-14 12:13:52