代码之家  ›  专栏  ›  技术社区  ›  xmllmx

在C++20中,是否有一种优雅的方式在编译时对类型进行排序?

  •  0
  • xmllmx  · 技术社区  · 4 月前

    考虑以下代码:

    #include <concepts>
    
    struct T1 {};
    
    struct T2 {};
    
    struct T3 {};
    
    struct T4 {};
    
    void bar(T1, T2, T3, T4) {
    }
    
    template<typename T>
    concept IsT = std::same_as<T, T1> || std::same_as<T, T2> ||
                  std::same_as<T, T3> || std::same_as<T, T4>;
    
    void foo(IsT auto x1, IsT auto x2, IsT auto x3, IsT auto x4) {
        // How to sort the types of x1, x2, x3, x4 and call bar(x?, x?, x?, x?)?
    }
    
    int main() {
        foo(T1{},T2{},T3{},T4{}); // ok
        foo(T4{},T3{},T2{},T1{}); // ok
        foo(T3{},T2{},T1{},T4{}); // ok
        // ...
    }
    

    我的意图很简单:

    用户可以拨打 foo 以任何论证顺序,但最后 bar 将按排序的参数顺序调用。

    简单的解决方案是使用蛮力来划分24个案例,这显然是乏味且容易出错的。

    在C++20中,有没有一种优雅的方法来解决这个问题?

    1 回复  |  直到 4 月前
        1
  •  6
  •   Jarod42    4 月前

    由于类型不同,您可以将它们包装在元组中,然后获得正确的类型:

    void foo(IsT auto x1, IsT auto x2, IsT auto x3, IsT auto x4) {
        auto t = std::tie(x1, x2, x3, x4);
        bar(std::get<T1&>(t), std::get<T2&>(t), std::get<T3&>(t), std::get<T4&>(t));
    }
    

    Demo