c++ - 如何正确检查(常量)重载方法

标签 c++ template-meta-programming

我目前正在尝试编译以下内容:

class foo {
};

class bar {
public:
  const foo & to_foo() const {
    return f;
  }

  foo & to_foo() {
    return f;
  }
private:
 foo f;
};

template< typename T, typename Enable = void >
class convert {};

template< typename T >
struct convert< T, typename std::enable_if< std::is_member_function_pointer< decltype( &T::to_foo ) >::value >::type > {

  static const foo & call1( const bar & b ) {
    return b.to_foo();
  }

  static foo & call2( bar & b ) {
    return b.to_foo();
  }
};

然而,特化 get 因两个可能的 to_foo() 成员的存在而感到困惑,因此它将选择默认情况。一旦我删除其中一个 to_foo() 成员,它就可以工作,但是随后其中一个 callX() 方法失败,因为它与常量不匹配。

在这种情况下有什么方法可以检测到这个函数吗?

编辑:

这是一个关于ideone的例子:http://ideone.com/E6saX

当其中一种方法被删除时,它工作得很好:http://ideone.com/iBKoN

最佳答案

我仍然不太清楚您要实现的目标。我假设目标类型 (foo) 是固定的,我们不会尝试创建一个完整的桥接系统。

在这种情况下,我们可以放弃结构,只依赖重载选择。

foo const& to_foo(bar const& b) { return b.to_foo(); }
foo& to_foo(bar& b) { return b.to_foo(); }

就实际翻译而言,效果很好。不涉及模板。

现在的问题可能是如何实际检测这种转换是否可能。在这种情况下,我们需要使用 SFINAE 来避免在尝试转换时出现硬错误。

#include <iostream>
#include <utility>

// Didn't remember where this is implemented, oh well
template <typename T, typename U> struct same_type: std::false_type {};
template <typename T> struct same_type<T, T>: std::true_type {};

// Types to play with
struct Foo {};
struct Bar { Foo _foo; };
struct Bad {};

Foo const& to_foo(Bar const& b) { return b._foo; }
Foo& to_foo(Bar& b) { return b._foo; }

// Checker
template <typename T>
struct ToFoo {
  T const& _crt;
  T& _rt;

  template <typename U>
  static auto to_foo_exists(U const& crt, U& rt) ->
      decltype(to_foo(crt), to_foo(rt), std::true_type());

  static std::false_type to_foo_exists(...);

  // Work around as the following does not seem to work
  // static bool const value = decltype(to_foo_exists(_crt, _rt))::value;
  static bool const value = same_type<
                                decltype(to_foo_exists(_crt, _rt)),
                                std::true_type
                            >::value;
};

// Proof
int main() {
  std::cout << ToFoo<Bar>::value << "\n"; // true
  std::cout << ToFoo<Bad>::value << "\n"; // false
}

注意:在 Clang 3.0 上成功编译(有解决方法)和 gcc 4.5.1 .

关于c++ - 如何正确检查(常量)重载方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9580969/

相关文章:

c++ - 如何使用带有模板参数和参数包的 enable if?

c++ - 指向成员函数的指针的模板参数推导

c++ - 为什么 set __cache_hash_code 只能用于 std::unordered_map?

参数替换的 C++ 规则

c++ - 可变模板构造函数和移动构造函数

c++ - 模板模板可以专用于常规模板之类的基本类型吗?

c++ - if (NULL == pointer) 和 if (pointer == NULL) 有什么区别?

c++ - 为什么 "ostream & os"必须用于 C++ 运算符重载?

c++ - 函数模板的 typedef(部分实例化)

c++ - 将元组转换为模板中的结构