【问题标题】:Is it possible to define type alias to constexpr function是否可以为 constexpr 函数定义类型别名
【发布时间】: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


【解决方案1】:

根据 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 = 之后需要一个类型。

【讨论】:

    【解决方案2】:

    您不能为 constexpr 函数定义类型别名。

    【讨论】:

    • C++ 标准不支持这个有什么具体原因吗?
    猜你喜欢
    • 2011-06-20
    • 2020-08-24
    • 1970-01-01
    • 1970-01-01
    • 2012-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多