3

現在、次のものをコンパイルしようとしています。

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();
  }
};

ただし、特殊化は 2 つの可能なto_foo()メンバーの存在によって混乱するため、デフォルトのケースが選択されます。to_foo()メンバーの 1 つを削除するとすぐにcallX()機能しますが、constness と一致しないため、メソッドの 1 つが失敗します。

この場合、この機能を検出する方法はありますか?

編集

以下は ideone の例です: http://ideone.com/E6saX

メソッドの 1 つを削除すると、問題なく動作します: http://ideone.com/iBKoN

4

3 に答える 3

1

あなたが何を達成しようとしているのか、私にはまだ少し不明です。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で正常にコンパイルされました。

于 2012-03-06T10:29:27.050 に答える
0

テンプレートについてはまだよくわかりませんがis_const、関数がconst.

リンクはこちら

于 2012-03-06T09:41:47.487 に答える
-1

私のgcc(4.1.0)はc ++ 0xをサポートしていないので、std::enable_ifの部分を削除します。その後、コンパイルして正常に実行されます。参照: http: //ideone.com/KzasX

ありがとう

于 2012-03-06T10:38:13.803 に答える