在 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 aconstexpr
function or aconstexpr
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/