简体   繁体   中英

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?

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.

您无法为constexpr函数定义类型别名。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM