【发布时间】:2019-06-11 16:43:55
【问题描述】:
我正在尝试找到一种方法,使用 c++11 功能简单地检查给定名称的方法是否存在于 c++ 类中,但不检查签名。
没有签名检查我无法找到任何东西,所以我尝试使用来自here 的 Valentin Milea 的解决方案并对其进行修改(见下文),但我对 c++ 的理解还不够深入,无法真正掌握那里发生的事情:
#include <type_traits>
template <class C>
class HasApproxEqualMethod
{
template <class T>
static std::true_type testSignature(bool (T::*)(const T&, double) const);
template <class T>
static decltype(testSignature(&T::approx_equal)) test(std::nullptr_t);
template <class T>
static std::false_type test(...);
public:
using type = decltype(test<C>(nullptr));
static const bool value = type::value;
};
class Base {
public:
virtual ~Base();
virtual bool approx_equal(const Base& other, double tolerance) const;
};
class Derived : public Base {
public:
// same interface as base class
bool approx_equal(const Base& other, double tolerance) const;
};
class Other {};
static_assert(HasApproxEqualMethod<Base>().value == true, "fail Base");
static_assert(HasApproxEqualMethod<Other>().value == false, "fail Other");
// this one fails:
static_assert(HasApproxEqualMethod<Derived>().value == true, "fail Derived");
我认为问题的根源在于我的approx_equal 在派生类中也使用了基类引用,并且不再与签名匹配。
最后,我想构造一个模板比较函数,如果它存在则调用 approx_equal 或其他东西(例如 == 用于字符串等,或 fabs(a-b) <= tolerance 用于浮点数和双精度数)。然后 approx_equal 函数将依次调用每个成员的模板比较。
实际上,我让这部分使用了一个丑陋的解决方法,其中每个具有approx_equal 方法的类也获得一个成员变量const static char hasApproxEqualMethod。然后我检查该变量是否按照here 的建议存在,但这肯定不是要走的路。
【问题讨论】:
-
this question 的答案应该会派上用场。只需将
operator()替换为approx_equal。
标签: c++ c++11 templates methods sfinae