将值注入枚举

时间:2017-04-09 16:46:00

标签: c++ enums

我有摘录:

enum class EnumClass {
};

constexpr EnumClass m0 = static_cast<EnumClass>(0);
constexpr EnumClass m1 = static_cast<EnumClass>(1);

int main()
{
    EnumClass aa = m0;
    switch (aa) {
        case m0 : break;
        case m1 : break;
    }
}

带有-Wall标志的Gcc 7.0合理警告我:

warning: case value '0' not in enumerated type 'EnumClass' [-Wswitch]
warning: case value '1' not in enumerated type 'EnumClass' [-Wswitch]

我想要的是摆脱这个警告。假设有很多这样的开关,所以每次手动关闭/打开此警告并不是很方便。此外,我不想全局关闭此诊断。

我想要的是以某种方式(可能在EnumClass定义中使用一些宏)向编译器说任何可能的int值都可以在EnumClass中。有人可以提出一些想法如何实现吗?

1 个答案:

答案 0 :(得分:1)

我仍然不明白您的最终目标是什么,但是,假设您想要阻止仅在代码的某些特定部分生成using System; using System.Threading; using System.Collections.Generic; using System.Linq; namespace Rextester { public class Program { public static void Main(string[] args) { private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { int sum = 0; for (int i = 1; i <= 100; i++) { // run the process here Thread.Sleep(100); // end process sum = sum + i; backgroundWorker1.ReportProgress(i); if (backgroundWorker1.CancellationPending) { e.Cancel = true; backgroundWorker1.ReportProgress(0); return; } } // displays the sum of the process e.Result = sum; } private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e) { progressBar1.Value = e.ProgressPercentage; label5.Text = e.ProgressPercentage.ToString() + "%"; DateTime starttime = DateTime.Now; var timespent = DateTime.Now - starttime; double secondsremaining = (double)(timespent.TotalSeconds / progressBar1.Value) * (progressBar1.Maximum - progressBar1.Value); label7.Text = "Time remaining:" + (int)secondsremaining; Console.WriteLine(secondsremaining); } private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e) { if (e.Cancelled) { label5.Text = "Processing Cancelled"; } else if (e.Error != null) { label5.Text = e.Error.Message; } else { label5.Text = "Sum = " + e.Result.ToString(); } label6.Text = ""; } private void button11_Click_1(object sender, EventArgs e) { //Checks if the background worker is busy running operations if (!backgroundWorker1.IsBusy) { //this method will start the excution of the opreation backgroundWorker1.RunWorkerAsync(); } else { label6.Text = "The operation is being completed, please wait..."; } } } } } 警告,您可以使用{{1指令如下:

-Wswitch

live wandbox example

这不会全局停用#pragma - 它会在int main() { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wswitch" EnumClass aa = EnumClass::m0; switch (aa) { case EnumClass::m0 : break; case EnumClass::m1 : break; case static_cast<EnumClass>(888) : break; } #pragma GCC diagnostic pop } 行恢复。