c++ - 是否可以为 constexpr 函数定义类型别名

标签 c++ c++11 constexpr type-alias

在 C++11 或 C++14 中,我试图为 constexpr 函数定义类型别名。

我试过:

#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;
}

但它无法使用 g++ 和 clang++ 进行编译。

g++: 错误:“constexpr”之前需要类型说明符

clang ++: 错误:类型名称不允许指定 constexpr 说明符

我必须按照下面的方式进行编译

#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;
}

从 clang++ 的错误消息来看,我似乎不能使用 constexpr 作为类型名称。

那么,是否可以为 constexpr 函数定义类型别名?如果是,如何?

最佳答案

根据 C++ 标准 7.1.5/p8 constexpr 说明符 [dcl.constexpr](强调我的):

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

同样来自 7 声明 [dcl.dcl]:

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

constexpr 说明符不是函数类型的一部分。因此,您不能:

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

因为在 using TConstExprFunction = 之后需要一个类型。

关于c++ - 是否可以为 constexpr 函数定义类型别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37993732/

相关文章:

c++如何从一个函数的多个派生类中调用纯虚方法?

c++ - 结构体中的友元函数有什么用?

c++ - 如果我的类是文字类,那么将我的类的对象声明为 constexpr 是否多余?

c++ - QObject::deleteLater 在我的 Qt 测试中没有按预期调用

c++ - C++单继承的内存布局和这个C代码一样吗?

c++ - CMake发现不止一个main函数

c++ - 如果它包含多个语句,是否有理由不允许 lambdas 推断返回类型?

c++ - move 构造函数可以是隐式的吗?

c++ - 数组初始化编译时间 - Constexpr 序列

c++ - 静态模板化 constexpr 嵌套类成员