c++ - MSVS/MSVC 静态模板类方法不警告

标签 c++ visual-studio visual-c++ static

前一段时间,这个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/

相关文章:

.net - 哪个是最重要的代码分析规则,为什么?

c++ - 访问指针句柄中对象的地址

c++ - 如何将 typedef 用作声明基类型的一部分?

使用opencv进行c++视频捕获

visual-studio - MS VC++ 如何在不需要 vc redist 的情况下构建 DLL

c# - 在 HttpClient 上取消异步和等待不会在 OSX 上抛出异常

directory - 如何在解决方案级别添加额外的包含目录?

c++ - 用C中的文本文件的内容初始化一个数组

visual-c++ - 在不同嵌套级别的多个项目中包含公共(public)资源(Visual C++)

c++ - 如何实现具有不同签名的虚函数?