35

私がtemplate関数を持っているとしましょう:

template<typename T>
T produce_5_function() { return T(5); }

templateこの全体を別の人に渡すにはどうすればよいtemplateですか?

ファンクターであればproduce_5_function、問題はありません。

template<typename T>
struct produce_5_functor {
  T operator()() const { return T(5); }
};
template<template<typename T>class F>
struct client_template {
  int operator()() const { return F<int>()(); }
};
int five = client_template< produce_5_functor >()();

しかし、生の関数テンプレートを使用してこれを実行できるようにしたいと思います。

template<??? F>
struct client_template {
  int operator()() const { return F<int>(); }
};
int five = client_template< produce_5_function >()();

答えは「これはできない」と思います。

4

2 に答える 2

23

答えは「これはできない」と思います。

はい、その場合、関数テンプレートをテンプレート引数として渡すことはできません。14.3.3から:

テンプレートtemplate-parameterのtemplate-argumentは、クラステンプレートまたはエイリアステンプレートの名前であり、id-expressionとして表されます。

テンプレート関数は、他のテンプレートに渡す前にインスタンス化する必要があります。produce_5_function考えられる解決策の1つは、次のような静的を保持するクラス型を渡すことです。

template<typename T>
struct Workaround {
  static T produce_5_functor() { return T(5); }
};
template<template<typename>class F>
struct client_template {
  int operator()() const { return F<int>::produce_5_functor(); }
};
int five = client_template<Workaround>()();

エイリアステンプレートを使用すると、もう少し近づくことができます。

template <typename T>
T produce_5_functor() { return T(5); }

template <typename R>
using prod_func = R();

template<template<typename>class F>
struct client_template {
  int operator()(F<int> f) const { return f(); }
};

int five = client_template<prod_func>()(produce_5_functor);
于 2013-03-27T04:10:49.703 に答える
6

その関数をラップするのはどうですか?

template<typename T>
struct produce_5_function_wrapper {
    T operator()() const { return produce_5_function<T>(); }
};

次に、関数の代わりにラッパーを使用できます。

int five = client_template< produce_5_function_wrapper >()();

テンプレート関数だけでは動作せず、「テンプレートテンプレート関数」などはありません。

于 2013-03-27T03:51:48.597 に答える