前一段时间,这个question被问到,关于熟悉的
error: 'static' can only be specified inside the class definition
错误。
在我当前的用例中,我正在从一个非常 MSVC 的项目转移,其中几乎所有代码都是使用 MSVC 编译的,并针对 Android 进行交叉编译。
I noticed that there is no MSVC error, least of all, a warning, about static class methods having definitions inside (outside) the class. Am I missing something? Why is there not at least a warning?
编辑
为了澄清,我问的是为什么没有针对此类代码的适当 MSVC/MSVS 警告(取自上面的链接):
class Foobar {
public:
static void do_something();
};
static void Foobar::do_something() {} // Error!
int main() {
Foobar::do_something();
}
编辑
对不起大家!这个示例不起作用!我很抱歉。
class Foobar {
public:
template<class Y>
static int do_something();
};
template<class Y>
static int Foobar::do_something() {return 1;} // Error!
int main() {
return Foobar::do_something<double>();
}
这是 MSVC 19.14 的输出(成功)和 GCC 4.12 (失败)。
最佳答案
VS 2012 Update 5、VS 2013 Update 5、VS 2015 Update 3 和 VS 2017(15.9 更新)都针对这段代码报错:
error C2724: 'Foobar::do_something': 'static' should not be used
on member functions defined at file scope
我猜测代码仅使用旧的、不一致的 Visual C++ 版本构建。
请注意,如果您想使用 Visual C++ 编译器清理代码以使其更容易移植到其他平台:
您可以使用带有
/permissive-
开关的 VS 2017。参见 this blog post .还有许多一致性开关可供尝试,例如
/Zc:__cplusplus
。参见 this blog post .
Using
/permissive-
already implies/Zc:strictStrings
,/Zc:rvalueCast
, and/Zc:ternary
and enables two-phase name look-up.
您也可以使用
/Wall
,尽管需要一些努力才能降低所有噪音以查看有用的警告。它仍然不像clang
那样挑剔,但它很有用。有关要抑制的一堆内容的示例,请参阅 this header 的顶部.还有一个您可以试用的实验性 C99 预处理器,尽管它仍处于早期阶段。参见 this blog post
You can try it out yourself with the VS 2017 Community edition.
关于c++ - MSVS/MSVC 静态模板类方法不警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53343030/