WIN32编程不能包括模板标头文件



我正在使用Visual Studio 2017编写标准Win32 Windows UI程序。但是,当我尝试将以下标题文件包含到myMainWin.cpp文件(您定义Windows和消息处理)时,它抱怨许多语法错误。例如,它抱怨"出乎意料的令牌";'';'"对于类定义末尾的行"};";如果我将以下标头文件包含到控制台应用程序main.cpp中,则效果很好。为什么?

#ifndef _MY_RAND_H_
#define _MY_RAND_H_
#include <random>
#include <tuple>
#include <iostream>
namespace myown {
void srand(int seed);
int rand();
template<class IntType = int>
class my_uniform_int_distribution {
public:
// types
typedef IntType result_type;
typedef std::pair<int, int> param_type;
// constructors and reset functions
explicit my_uniform_int_distribution(IntType a = 0, IntType b = std::numeric_limits<IntType>::max());
explicit my_uniform_int_distribution(const param_type& parm);
void reset();
// generating functions
template<class URNG>
result_type operator()(URNG& g);
template<class URNG>
result_type operator()(URNG& g, const param_type& parm);
// property functions
result_type a() const;
result_type b() const;
param_type param() const;
void param(const param_type& parm);
result_type min() const;
result_type max() const;
private:
typedef typename std::make_unsigned<IntType>::type diff_type;
IntType lower;
IntType upper;
}; //visual studio compiler complains "unexpected token(s) preceding';'" here
//method definition...
}
#endif

您可能会遇到问题,因为您使用std::numeric_limits<IntType>::max()windows.h最终包括一个文件minwindef.h,该文件定义了不幸的宏maxminminwindef.h的摘要:

#ifndef NOMINMAX
#ifndef max
#define max(a,b)            (((a) > (b)) ? (a) : (b))
#endif
#ifndef min
#define min(a,b)            (((a) < (b)) ? (a) : (b))
#endif
#endif  /* NOMINMAX */

如果在您的自定义标题之前包括windows.h,则std::numeric_limits<IntType>::max()表达式将扩展到std::numeric_limits<IntType>::((() > ()) ? () : ()),这是无效的语法。

有两种可能的解决方案:

  • #define NOMINMAX在包括windows.h之前 - 这是一个很好的做法,因为这些min/max宏(及其非窗口表格MINMAX)是已知的问题原因
  • windows.h之前包括您的自定义标头 - 这不是最好的方法,因为它要求您的自定义标头的用户拥有一些其他知识

最新更新