如何在C ++ 11中使用constexpr函数和参考参数?

时间:2016-01-14 15:13:15

标签: c++ c++11 constexpr

我最近学习了constexpr函数,我编写了一个函数,通过检查它们的地址来检查两个字符串是否是同一个对象(仅仅是为了好奇)。函数编译正确,但是当我尝试调用该函数时似乎发生了一些问题。

理论上,如果函数的参数是常量表达式,函数将返回一个常量表达式,否则,它将像普通函数一样运行。所以在代码的第一部分,我尝试用const变量调用该函数。在第二部分中,我用非const变量调用函数。

以下是我的代码。我使用Visual Studio Community 2015.编译器警告我有两个我在下面用^标记的错误,但代码仍然可以编译和运行。

#include <iostream>
#include <string>

constexpr bool isSameString(const std::string &s1, const std::string &s2) {
    return &s1 == &s2;
}

int main() {
    //constexpr std::string s("p");  // No constexpr constructor
    static const std::string s1("a");
    static const std::string s2("a");
    static const std::string s3("b");

    // Right return value in editor, wrong when running.
    constexpr bool b1 = isSameString(s1, s1);

    // Error in editor(but can still compile), wrong when running.
    constexpr bool b2 = isSameString(s1, s2);
                     // ^^^^^^^^^^^^ Error

    // Error in editor(but can still compile), wrong when running.
    constexpr bool b3 = isSameString(s1, s3);
                     // ^^^^^^^^^^^^ Error

    std::cout << b1 << " " << b2 << " " << b3 << std::endl;

    /********************************************************************/

    std::string s4("x");
    std::string s5("x");
    std::string s6("y");

    std::cout << isSameString(s4, s4) << " "         // Right return value
              << isSameString(s4, s5) << " "         // Right return value
              << isSameString(s4, s6) << std::endl;  // Right return value

    std::cin.get();
}

所以,

  1. 有没有办法解决这两个错误?
  2. 为什么代码仍然可以编译并运行这些错误?
  3. 为什么编辑器和运行时b1的值不同?
  4. 有没有办法正确调用返回constexpr
  5. 的函数

    如果有人能帮助我,我将不胜感激:)

    修改

    我知道std::string不是文字类型,但引用是文字类型。问题是关于如何使用constexpr 功能。所以我认为它与this question没有重复。

0 个答案:

没有答案