在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 : error: expected type-specifier before 'constexpr'
clang : error: type name does not allow constexpr specifier to be specified
我必须在下面做才能使其编译
#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
用于类型名称。
so,可以将类型的别名定义为constexpr函数。如果是,如何?
根据C 标准 7.1.5/p8 constexpr
指定器[dcl.constexpr] (重点是Mine ):
constexpr
指示符对constexpr
的类型没有影响 功能或constexpr
构造函数。
也来自 7声明[dcl.dcl] :
alias-declaration: using identifier attribute-specifier-seqopt = defining-type-id ;
constexpr
指示符不是函数类型的一部分。因此,您不能做:
using TConstExprFunction = constexpr int (*)(int i, int j);
因为在using TConstExprFunction =
之后,预期是一种类型。
您不能为constexpr函数定义类型别名。