Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare a function signature with decltype()

Is it possible to declare a function bar to have the same signature as function foo?

int foo(int a)
{
    return 0; 
}

decltype(foo) bar
{
    return 1;
} //imaginary syntax
like image 848
Lorenzo Pistone Avatar asked Jan 10 '14 21:01

Lorenzo Pistone


People also ask

What is the decltype of a function?

If the expression parameter is a call to a function or an overloaded operator function, decltype(expression) is the return type of the function. Parentheses around an overloaded operator are ignored. If the expression parameter is an rvalue, decltype(expression) is the type of expression.

How does decltype work in C++?

The decltype type specifier yields the type of a specified expression. The decltype type specifier, together with the auto keyword, is useful primarily to developers who write template libraries. Use auto and decltype to declare a template function whose return type depends on the types of its template arguments.

What is the difference between auto and decltype in C++?

'auto' lets you declare a variable with a particular type whereas decltype lets you extract the type from the variable so decltype is sort of an operator that evaluates the type of passed expression.


1 Answers

I think the same applies as for typedefs and aliases: You may use decltype to declare a function, but not to define it:

int foo();

decltype(foo) bar;

int foo()
{
    return bar();
}

int bar() { return 0; }

is accepted by clang++3.5 and g++4.8.1


[dcl.fct.def.general]/2 forbids (grammatically) the definition of a function w/o parentheses:

The declarator in a function-definition shall have the form

       D1 ( parameter-declaration-clause ) cv-qualifier-seqopt ref-qualifieropt exception-specificationopt attribute-specifier-seqopt trailing-return-typeopt

as described in 8.3.5.

like image 113
dyp Avatar answered Nov 17 '22 01:11

dyp