局部专业化的默认参数
|
我想在用户端实现什么语法:
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和wrapper类,但是不能将静态成员分配给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
};
没有找到相关结果
已邀请:
3 个回复
授巨
您无法做到这一点:模板参数不能是
类型的值(它们可以是
类型的左值,但是您的模板需要
的地址,因此\处于关闭状态)。 您可以使用功能模板来使语法正常工作
另外,如果您打算接受一些丑陋的技巧,则可以使用类模板
如果您同时提供两个参数,则将不使用默认参数。如果仅提供“ 9”,则将使用默认参数并将其起作用。如果仅提供
,则也将使用默认参数,但将不起作用。
土投
暑袜眠退
然后在需要特定的epsilon时:
并使用它: