[英]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'
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
作為類型名稱。
那么,是否可以為constexpr函數定義一個類型別名; 如果有,怎么樣?
根據C ++標准7.1.5 / p8 constexpr
說明符[dcl.constexpr] ( Emphasis 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函數定義類型別名。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.