是否可以为 constexpr 函数定义类型别名
Is it possible to define type alias to constexpr function
在 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'
当当++:
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
作为类型名称。
那么,是否可以为 constexpr 函数定义类型别名;如果是,如何?
您不能为 constexpr 函数定义类型别名。
根据 C++ 标准 7.1.5/p8 constexpr
说明符 [dcl.constexpr] (Emphasis Mine):
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++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'
当当++:
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
作为类型名称。
那么,是否可以为 constexpr 函数定义类型别名;如果是,如何?
您不能为 constexpr 函数定义类型别名。
根据 C++ 标准 7.1.5/p8 constexpr
说明符 [dcl.constexpr] (Emphasis Mine):
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 =
之后需要一个类型。