Suppose I have this function template:
template<typename T1, typename T2>
auto DoSomething(const T1& arg);
Of course this function needs a trailing return type which, considering the function’s purpose, I really could not get right.
What this function is supposed to do is to use arg, do some operation with arg and a T2 object and use the result of that operation as the return value of the function. Clearly, DoSomething()‘s return type must (compatibly) match with the return type of the operation done for arg and the T2 object.
Suppose again that we make DoSomething() do some real operation, like multiplication. We would then write DoSomething() as like the code below:
template<typename T1, typename T2>
auto DoSomething(const T1& arg) -> /* trailing return-type */ {
T2 t2Obj; // Or have it obtained in some other way
return arg * t2Obj;
}
How should I then form the trailing return-type for this?
P.S.: I’ve tried using decltype(arg * T2), decltype(T1 * T2) and decltype(T1::operator * (T2)) and some other really bizarre-looking decltypes for the trailing-return type. None of them worked.
You should use
decltypeandstd::declval<>as:because
T2might not have default constructor, sodecltype(arg *T2())may not work.But then I also notice that if
T2doesn’t have default constructor, then you would not be able to writeT2 t2Objeither. So if you requireT2to have default constructor, then you can simply write this:that should also work if you require
T2to have default constructor!