使用static_assert以确保模板参数仅*最多*使用一次

时间:2019-05-21 11:41:12

标签: c++ c++11 templates static-assert

是否可以确保最多使用一次某个模板参数(或模板参数的组合)?是否可以跟踪它的使用次数,并且如果多次使用它会抛出static_assert错误?

作为示例-假设我想创建一个基于模板的静态GPIO类:

struct Board {
  Gpio<1, 1> myInputPin;
  Gpio<1, 2> myOutputPin;

  Gpio<2, 0> ledR;
  Gpio<2, 1> ledG;
  Gpio<2, 2> ledB;
};

一个人可以将整个董事会布置在一个董事会班上:

Option Explicit

Sub CopyYes()

    Dim cell As Range
    Dim Source As Worksheet, Target As Worksheet

    With ThisWorkbook
        Set Source = .Worksheets("PersonalInfo")
        Set Target = .Worksheets("FullpInfo")
    End With

    With Target

        'Formatting
        Call Module1.Formatting(.Range("B3"), "Name", "Titles")
        Call Module1.Formatting(.Range("D3"), "Drink", "Titles")
        Call Module1.Formatting(.Range("B6"), "Food", "Titles")
        Call Module1.Formatting(.Range("D6"), "Vehicle", "Titles")

        For Each cell In Source.Range("E2:E100")

            If cell.Value = "yes" Then

                'Values
                Call Module1.Formatting(.Range("B4"), Source.Range("A" & cell.Row).Value, "Values")
                Call Module1.Formatting(.Range("D4"), Source.Range("C" & cell.Row).Value, "Values")
                Call Module1.Formatting(.Range("B7"), Source.Range("B" & cell.Row).Value, "Values")
                Call Module1.Formatting(.Range("D7"), Source.Range("D" & cell.Row).Value, "Values")

            End If

        Next cell

    End With

End Sub

Sub Formatting(ByVal rng As Range, str As String, strType As String)

    With rng
        .Value = str
        .Font.Bold = True
        If strType = "Values" Then
            .Font.Color = vbBlue
        End If
    End With

End Sub

对于任何给定的端口/引脚组合,仅对于该端口和引脚实例化单个 GPIO模板才有意义。如果有人为相同的端口/引脚组合创建两个不同的GPIO实例,则可能表示冲突,我想在编译过程中捕获此错误。

这可能吗?

1 个答案:

答案 0 :(得分:2)

您可以使用宏解决此问题:

#define GPIO(Port, Pin) \
    friend void _gpio_ ## Port ## _ ## Pin(){} \
    Gpio<Port, Pin>

然后,如果您两次使用GPIO(2, 2),则编译器将显示以下内容:

error: redefinition of '_gpio_2_2'
  GPIO(2, 2) ledX;
  ^

<source>:14:3: note: previous definition is here
  GPIO(2, 2) ledB;
  ^

演示:https://godbolt.org/z/ronV0u