On Thu, 16 Oct 2014 08:47:25 -0500
Robert Hutchings <rm.hutchings@gmail.com> wrote:
I was given this code yesterday:
#ifndef _MEMOIZE_H_
#define _MEMOIZE_H_
#include <tuple>
#include <map>
template < typename T > struct Memoize
{
template <typename... Args> static auto Func(Args... args)
-> decltype(T::Func(std::forward<Args>(args)...))
{
using INPUT = std::tuple<Args...>;
using RESULT = decltype(T::Func(std::forward<Args>(args)...));
static std::map< INPUT, RESULT > repository;
auto key = std::make_tuple(std::forward<Args>(args)...);
auto it = repository.find(key);
if (it != repository.end())
{
return it->second;
}
else
{
auto result = T::Func(std::forward<Args>(args)...);
repository[key] = result;
return result;
}
}
};
#endif // _MEMOIZE_H_
Now, can someone point me to a good tutorial or book on variadic
templates and the "using SOMETHING = " semantics. Is this just an
alias?
I usually begin with cpp.reference.com for this kind of thing. This
is a good reference on 'using' for defining types:
http://en.cppreference.com/w/cpp/language/type_alias
This might help with variadic templates, although it is a reference
rather than a tutorial and so assumes some knowledge:
http://en.cppreference.com/w/cpp/language/parameter_pack
using RESULT = decltype(T::Func(std::forward<Args>(args)...));
is the same as
typedef decltype(T::Func(std::forward<Args>(args)...)) RESULT;
This is defective:
template <typename... Args> static auto Func(Args... args)
-> decltype(T::Func(std::forward<Args>(args)...))
If forwarding of rvalues as well as lvalues is to be achieved the
signature should be:
template <typename... Args> static auto Func(Args&&... args)
-> decltype(T::Func(std::forward<Args>(args)...))
Chris
OK, thanks for the tips. I will check out cppreference.com.