3

void(* func)(T)型とfuncの引数argの関数をとるファンクターFを書いています。

template<typename T>
  void F(void (*func)(T), WhatTypeHere? arg)
{
  func(arg);
}

次に、ファンクターFはargを使用してfuncを呼び出します。Fはargをコピーせず、参照として渡すだけにします。しかし、Tが参照になる可能性があるため、単純に「void F(void(* func)(T)、T&)」と書くことはできません。だから私はTの適切な参照型を取得することを可能にする特性を書き込もうとしています:

T -> T&
T& -> T&
const T -> const T&
const T& -> const T&

私はこのようなものを思いつきます:

template<typename T>
 struct type_op
{
 typedef T& valid_ref_type;
};

template<typename T>
 struct type_op<T&>
{
 typedef typename type_op<T>::valid_ref_type valid_ref_type;
};

template<typename T>
 struct type_op<const T>
{
 typedef const T& valid_ref_type;
};

template<typename T>
 struct type_op<const T&>
{
 typedef const T& valid_ref_type;
};


template<typename T>
  void F(void (*func)(T), typename type_op<T>::valid_ref_type arg)
{
  func(arg);
}

たとえば、これは機能しません

void a(int x) { std::cout << x << std::endl; }
F(&a, 7);

エラーの発生:「voidF(void(*)(T)、typename type_op :: valid_ref_type)[with T = int]'</ p>

この特性を機能させる方法は?

4

4 に答える 4

5
template<class T>
struct forwarding { typedef T const& type; };
template<class T>
struct forwarding<T&> { typedef T& type; };

template<typename T>
void F(void (*func)(T), typename forwarding<T>::type arg) {
  func(arg);
}

void a(int x) { std::cout << x << std::endl; }
int main() {
  F(&a, 7);
}

あなたのマッピングは近かった、あなたは実際にTをT const&にもマッピングしたい:

T-> T const&
T&-> T&
T const&-> T const&

パラメータタイプがTconstの関数には、T!のシグニチャがあることに注意してください。constは、実装の詳細です。

void f(int const);
typedef void F(int); // typedef of function type
F* p = &f; // no error! f's signature doesn't include const
于 2010-04-13T10:32:58.963 に答える
2

必要なのは、参照を削除することだけです。

template<typename T> struct remove_reference { typedef T type; };
template<typename T> struct remove_reference<T&> { typedef T type; };

次に、次のように再度追加します。

remove_reference<T>::type&

関数は次のように宣言する必要があります。

template<typename T>
void F( void (*func)(T), const typename remove_reference<T>::type& arg )
{
  func(arg);
}
于 2010-04-13T10:26:26.960 に答える
1

私の頭の中では少し曖昧ですが、boost(おそらくboost :: bind)は、const T&特性を提供するだけでこれを解決ref(x)し、非定数参照を示すためにを使用する必要があると思います。

于 2010-04-13T10:28:13.773 に答える
1

add_referenceBoost.TypeTraitsから使用して、必要なタイプマッピングを実現することもできます。

于 2010-04-13T11:59:27.860 に答える