Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deduced return type with function template

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?

like image 774
cigien Avatar asked May 16 '20 00:05

cigien


People also ask

What is the return type of template function?

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.

What is template argument deduction in C++?

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&& .

What is function template with example?

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++.

What happens when a function is defined as a template?

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.


1 Answers

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.

like image 185
Fedor Avatar answered Sep 30 '22 14:09

Fedor