为什么不能将静态constexpr成员变量传递给函数?

问题描述 投票:1回答:2

以下代码生成undefined reference to 'Test::color'

#include <iostream>

struct Color{
    int r,g,b;
};

void printColor(Color color) {
    //printing color
}

class Test {
    static constexpr Color color = {242,34,4};
public:
    void print(){
        printColor(color);
    }
};


int main() {
    Test test;
    test.print();

    return 0;
}

为什么这个代码产生上述错误以及避免它的最佳方法是什么,考虑到我想使用最新版本的标准C ++ 17?

我应该定义静态成员变量,就像它在标准的早期版本中所需要的那样(参见第一个答案:Undefined reference to static constexpr char[])或者我应该创建一个新的Color结构,如下所示?

printColor(Color{color.r, color.g, color.b});

编辑:我在Ubuntu 16.04上使用CLion,据我所知,它使用g ++ 5.4进行编译。我已将其设置为使用C ++ 17并仍然得到相同的错误。只有当color传递给函数时才会出现错误。

c++ inline c++17 constexpr static-members
2个回答
3
投票

这是因为在C ++ 17之前,你必须在类之外专门定义静态变量:

class Test { 
   /* ... etc etc ... */
}

const constexpr Color Test::color;

静态成员的constexpr-ness不会让你“放弃”这个明确的定义要求。

使用C ++ 17,您不再需要显式定义静态成员。它们是隐式的“内联”变量,它们在某些时候自动定义,每个二进制只需一次,而不必处理它。有关此功能的长篇建议,请参阅here

请注意,该定义必须仅出现在单个翻译单元中(因此可能不会出现在包含Test的类的标题中)。


1
投票

问题既不是代码本身,也不是使用标准。 CLion的默认编译器并不完全支持C ++ 17,因此它显示了一个奇怪的行为,它可以编译static constexpr成员变量,但只要它们没有传递给函数。

更新到最新的编译器版本后,我能够成功运行代码而无需任何更改。

感谢您的所有贡献。

© www.soinside.com 2019 - 2024. All rights reserved.