相关疑难解决方法(0)

为什么MSVC++ 11拒绝对函数进行constexpr限定?

因此,使用constexpr,MSVC(Visual Studio 2012)在尝试constexpr使用此简单程序(包括省略)使用关键字限定我的函数时给了我一个错误:

constexpr int factorial(int n)
{
    return n <= 1 ? 1 : (n * factorial(n-1));
}

int main(void)
{
    const int fact_three = factorial(3);
    std::cout << fact_three << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

constexpr 带有以下消息的红色下划线:

错误:此声明没有存储类或类型说明符

并尝试编译该程序给出了以下输出:

1> main.cpp(5):错误C2144:语法错误:'int'前面应加';'

1> main.cpp(5):错误C4430:缺少类型说明符 - 假定为int.注意:C++不支持default-int

它真的让我感到困惑,因为它是Cppreference 用来说明其使用constexpr的一个例子.起初我使用了一个返回文字的简单函数,即constexpr int func(){return 5;}但产生了同样的错误.我将第一条消息解释为"它应该是结构或类的成员函数",但Cppreference的示例显示它显然不是必需的.

那么,我在这里明显缺少什么?

c++ constexpr c++11 visual-studio-2012

38
推荐指数
1
解决办法
7100
查看次数

为什么必须在运行时构造字符串?

可以在运行时创建C-Strings还是std::string必须创建constexpr它们?

使用gcc 4.9.2我可以这样做:

constexpr const char foo[] = "blee";
Run Code Online (Sandbox Code Playgroud)

(遗憾的是,2013年11月的客户技术预览版不允许Visual Studio支持此功能:https://stackoverflow.com/a/29255013/2642059)

但即使使用gcc 4.9.2我也不能这样做:

constexpr const std::string foo = "blee";
Run Code Online (Sandbox Code Playgroud)

我收到错误:

error: the type 'const string {aka const std::basic_string<char>}' of constexpr variable 'foo' 
       is not literal

 constexpr const std::string foo = "blee";
                                   ^
note: 'std::basic_string<char>' is not literal because:
     class basic_string
           ^
note:   'std::basic_string<char>' has a non-trivial destructor
Run Code Online (Sandbox Code Playgroud)

但我想更多地澄清为什么 a std::string不是文字.也就是说:为什么必须在运行时构造字符串?

正如所指出的,这个问题可以部分回答:是否可以在constexpr中使用std :: string?但它没有涉及为什么std::string不能成为问题核心的文字.

c++ literals stdstring constexpr c++11

23
推荐指数
2
解决办法
2092
查看次数

标签 统计

c++ ×2

c++11 ×2

constexpr ×2

literals ×1

stdstring ×1

visual-studio-2012 ×1