Consider the following program:
#include<functional>
template<typename T>
T f() { return T{}; }
template<typename T>
auto g() { return T{}; }
int main() {
std::function<int()> a = f<int>; // ok, clang and gcc
std::function<int()> b = g<int>; // ok, clang, error gcc
}
The error in gcc is
error: conversion from '<unresolved overloaded function type>' to non-scalar type 'std::function<int()>' requested
Here's the code to experiment with.
I don't understand why the program compiles only if the return type is T
, and fails on gcc when the return type is deduced.
Edit: The comments suggest this is a gcc bug, but could I get a confirmation that the program is indeed well formed?
The return type of the function template sum is that type to which the arithmetic expression evaluates. Here is what I don't like about this C++11 syntax: You have to use two times the same expression t + t2 . This is error-prone and redundant.
In the initialization of variable b , the template argument 1 is an rvalue, so the rvalue reference type int&& remains in the template instantiation. In the initialization of c , the template type parameter T&& is cv-qualified, but var is an lvalue, so var cannot be bound to the rvalue reference T&& .
Function Templates We write a generic function that can be used for different data types. Examples of function templates are sort(), max(), min(), printArray(). Know more about Generics in C++.
Function templates are special functions that can operate with generic types. This allows us to create a function template whose functionality can be adapted to more than one type or class without repeating the entire code for each type. In C++ this can be achieved using template parameters.
Indeed, f()
and g()
are similar functions, having the same result type.
It was just a bug in GCC, which is fixed in GCC 10.3. Clang and MSVC also accept the program, demo: https://gcc.godbolt.org/z/qPvar6vTh
So the program is well formed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With