Reputation: 1709
Let's say I have a template function that returns a dependent type. Something like:
template <class T>
typename std::result_of<T()>::type
foo()
{
std::result_of<T()>::type retVal;
// Some mind blowing code...
return retVal;
}
As you can see, I had to write the return type twice, once in the function type, and another time when declaring a local variable for the return value.
Is there a way I can typedef
this type in the function signature so the type will be declared only once (No code duplication) and be visible and usable only inside the function (signature and body)?
Something like (Warning! pseudo code ahead, please don't be annoyed or inspired):
template <class T>
typedef typename std::result_of<T()>::type FooReturnType
FooReturnType foo()
{
FooReturnType retVal;
// Some mind blowing code...
return retVal;
}
EDIT: I'm limited to a C++11 compiler.
Thanks
Upvotes: 1
Views: 137
Reputation: 180415
You can use a template parameter that gets set to std::result_of<T()>::type
like:
template <class T, class Ret = typename std::result_of<T()>::type>
Ret foo()
{
Ret retVal = 100;
// Some mind blowing code...
return retVal;
}
Upvotes: 1
Reputation: 8785
template <class T>
typename std::result_of<T()>::type
foo()
{
decltype(foo()) retVal;
// Some mind blowing code...
return retVal;
}
Upvotes: 3
Reputation: 473222
Is this not why we allowed template typedefs via using
?
template<typename T>
using Ret = typename std::result_of<T()>::type;
template<typename T>
Ret<T> foo()
{
Ret<T> retVal;
// Some mind blowing code...
return retVal;
}
If you won't accept the traditional C++98/03 solution of a default template parameter, and you won't accept the C++11 solution of adding a using
alias to the scope, and you can't use the C++14 solution of auto
return type deduction, then there is no solution.
Upvotes: 1
Reputation: 71899
As the comment says, there's this hack:
template <class T, typename Ret = std::result_of_t<T()>>
Ret foo() {
Ret retVal;
return retVal;
}
Alternatively, you might be able to simply use return type deduction if your compiler is new enough:
template <class T>
auto foo() {
std::result_of_t<T()> retVal;
return retVal;
}
Upvotes: 2