【发布时间】:2016-10-25 21:54:01
【问题描述】:
在 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 函数定义类型别名?如果是,怎么做?
【问题讨论】:
-
就像你不能在那里使用
static... -
"那么,是否可以为 constexpr 函数定义类型别名" 您可以为一个函数定义类型别名。你只是不能调用一个函数,就好像它是一个编译时常量表达式。所以你可能想要的效果是不可能的。
-
@MarcGlisse 说得通。
标签: c++ c++11 constexpr type-alias