c++ - 静态条件中的编译器警告

标签 c++ visual-studio visual-studio-2008 templates compiler-warnings

我使用模板参数来确定是否必须执行某个行为。但是此代码在 VS2008 上生成警告:Warning 26 warning C4127: conditional expression is constant

这里是代码的一个例子:

template <class param, bool param2=true>
class superclass1
{
public:
  int foo()
  {
     if(param2)
        doSomthingMore();

     return 1;
   }
};

有没有办法转换代码以删除警告并获得相同的功能?

最佳答案

这是通过部分特化完成的。最粗糙的版本如下所示:

template <typename, bool> class superclass1;

template <class param> class superclass1<param, true>
class superclass1
{
public:
  int foo()
  {
    doSomthingMore();
    return 1;
  }
};

template <class param> class superclass1<param, false>
class superclass1
{
public:
  int foo()
  {
    return 1;
  }
};

一种更复杂的方法可能会声明一个成员模板函数并且只特化那个。这是一个带有辅助标签类的解决方案:

#include <type_traits>

template <bool B> class Foo
{
  struct true_tag {};
  struct false_tag {};
  void f_impl(true_tag = true_tag()){}     // your code here...
  void f_impl(false_tag = false_tag()){}   // ... and here

public:
  void foo()
  {
    f(typename std::conditional<B, true_tag, false_tag>::type());
  }
};

关于c++ - 静态条件中的编译器警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8161778/

相关文章:

c++ - 错误 "does not name a type"和 "has not been declared"之间的区别

c++ - 我想在终端窗口中运行我的 CLion 程序

c++ - Visual Studio - 如何在显示消息框后捕获调试(中断)

python - 意外标记 'not' 仅在同一行中发生

c++ - 在线程错误 C2064 : term does not evaluate to a function taking 0 arguments

c++ - 将 C++ 头文件转换为 Python

c++ - 类型 `*` 对 __vfptr 意味着什么?

c# - 在类库中包含 View

c# - 如何在图像上绘制带有轮廓的文本?

c++ - 链接到库需要 MFC80U.LIB