C++11の次の関数について考えてみます。
template<class Function, class... Args, typename ReturnType = /*SOMETHING*/>
inline ReturnType apply(Function&& f, const Args&... args);
ReturnType
結果のタイプと等しくなりたいのですf(args...)
が、代わりに何を書く必要があり/*SOMETHING*/
ますか?
C++11の次の関数について考えてみます。
template<class Function, class... Args, typename ReturnType = /*SOMETHING*/>
inline ReturnType apply(Function&& f, const Args&... args);
ReturnType
結果のタイプと等しくなりたいのですf(args...)
が、代わりに何を書く必要があり/*SOMETHING*/
ますか?
trailing-return-typeを使用して関数テンプレートを次のように書き直す必要があると思います。
template<class Function, class... Args>
inline auto apply(Function&& f, const Args&... args) -> decltype(f(args...))
{
typedef decltype(f(args...)) ReturnType;
//your code; you can use the above typedef.
}
の代わりに args
asを渡す場合は、次のように使用することをお勧めします。Args&&...
const Args&...
std::forward
f
decltype(f(std::forward<Args>(args)...))
を使用する場合const Args&...
、std::forward
(少なくとも私にとっては)あまり意味がありません。
ユニバーサルリファレンスと呼ばれるものargs
として渡して使用することをお勧めします。Args&&...
std::forward
過負荷の解決には使用されないため、テンプレートパラメータである必要はありません。試す
template<class Function, class... Args>
inline auto apply(Function&& f, const Args&... args) -> decltype(f(std::forward<const Args &>(args)...));
std::result_ofの方が便利な場合があります。たとえば、次の関数を渡したいとします。
int ff(int& out, int in);
そしてapply()の中でそれをそのように呼びます
int res;
f(res, args...);
手元にint左辺値参照がないため、decltypeの使用方法がわかりません。result_ofを使用すると、変数は必要ありません。
template<class Function, class... Args>
typename std::result_of<Function(const Args&...)>::type apply(Function&& f, const Args&... args)
{
typedef typename std::result_of<F(const Args&...)>::type ReturnType;
// your code
}