This is a simplified example from a real issue that came up recently. There's easy workarounds, but I'd like to understand why the error occurs in the first place. Consider the following code:
#include <stdint.h>
struct Data
{
template <typename T>
T get_as() const
{
return static_cast<T>(value);
}
uint64_t value;
};
Data DoAdd(uint64_t input1, uint64_t input2)
{
return Data{input1+input2};
}
template<typename T>
T DoOperation(T input1, T input2)
{
return DoAdd(input1, input2).get_as<T>(); //Error, need template keyword
//return Data{input1+input2}.get_as<T>(); //Alternative 1, inline the operation: OK.
//Data value = DoAdd(input1, input2); //Alternative 2, break up into 2 steps: OK
//value.get_as<T>();
}
int main(int argc, const char** argv)
{
uint32_t one = DoOperation(1ULL, 2ULL);
return (one > 0);
}
Both GCC and clang warn that the keyword "template" is needed before get_as(), with clang's error being more useful:
<source>:22:34: error: use 'template' keyword to treat 'get_as' as a dependent template name
return DoAdd(input1, input2).get_as<T>();
^
template
However, I'm having trouble figuring out why the first line in DoOperation
is considered a dependent template that needs the template
keyword, but Alternative 1 and 2 are fine. If DoAdd
was a template function, or Data
itself was a templated struct, I think I'd see the problem, but since DoAdd
is a normal function and not dependent on T
, why does the expression DoAdd(input1, input2).get_as<T>()
trigger this behavior?