Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to define type alias to constexpr function

In C++11 or C++14, I'm trying to define a type alias to a constexpr function.

I tried:

#include <iostream>
constexpr int foo(int i, int j) { return i + j; }
using TConstExprFunction  = constexpr int (*)(int i, int j);

int main() {
  TConstExprFunction f = foo;
  constexpr int i = f(1, 2);
  std::cout << i << std::endl;
}

But it fails to compile with g++ and clang++.

g++: error: expected type-specifier before 'constexpr'

clang++: error: type name does not allow constexpr specifier to be specified

I have to do as below to make it compile

#include <iostream>
constexpr int foo(int i, int j) { return i + j; }
using TConstExprFunction  = int (*)(int i, int j);

int main() {
  constexpr TConstExprFunction f = foo;
  constexpr int i = f(1, 2);
  std::cout << i << std::endl;
}

From clang++'s error message, it seems I can NOT using constexpr for type name.

So, is it possible to define a type alias to a constexpr function; If yes, how?

like image 329
Mine Avatar asked Jun 23 '16 13:06

Mine


People also ask

Can you modify constexpr?

A const int var can be dynamically set to a value at runtime and once it is set to that value, it can no longer be changed. A constexpr int var cannot be dynamically set at runtime, but rather, at compile time. And once it is set to that value, it can no longer be changed.

Can constexpr functions call non constexpr functions?

A call to a constexpr function produces the same result as a call to an equivalent non- constexpr function , except that a call to a constexpr function can appear in a constant expression. The main function cannot be declared with the constexpr specifier.

Which is false about constexpr?

Short answer: static_assert(false) should never appear in a constexpr if expression, regardless of whether it's in a template function or whether it's in the discarded branch.


2 Answers

According to the C++ standard 7.1.5/p8 The constexpr specifier [dcl.constexpr] (Emphasis Mine):

The constexpr specifier has no effect on the type of a constexpr function or a constexpr constructor.

Also from 7 Declarations [dcl.dcl]:

alias-declaration:
using identifier attribute-specifier-seqopt = defining-type-id ;

constexpr specifier is not part of a function's type. Consequently, you can't do:

using TConstExprFunction  = constexpr int (*)(int i, int j);

Since after a using TConstExprFunction = a type is expected.

like image 113
101010 Avatar answered Oct 16 '22 20:10

101010


You cannot define a type alias to a constexpr function.

like image 32
Yakk - Adam Nevraumont Avatar answered Oct 16 '22 18:10

Yakk - Adam Nevraumont