【问题标题】:How to specify template arguments for templated operators如何为模板化运算符指定模板参数
【发布时间】:2020-03-29 12:57:59
【问题描述】:

我有一个模板化运算符作为类成员:

struct A {
  template <bool s=true> auto operator[](int ) {}
};

我以以下(相当繁琐)的方式指定模板参数:

int main() {
  A s;
  s.template operator[]<false>(1);
}

这种方式破坏了使用运算符的“美感”(除了使用模板化运算符可能不是最佳实践之外;我在代码中使用它来获得有条件的 const 返回类型而无需重新实现逻辑并仅在 at 实现内部使用模板)。

是否有更简洁的表示法来指定模板参数?

【问题讨论】:

    标签: c++ templates operator-overloading


    【解决方案1】:

    您可以将传递的参数包装在可以推断的模板类中,有点像标签调度:

    template<bool s>
    struct A_index {  // A shorter name based on your use case
        int i;
    };
    
    struct A {
        template<bool s> auto operator[](A_index<s> i_) {
            int i = i_.i;
            // Use `i`
        }
        auto operator[](int i) { (*this)[A_index<true>{ i }]; }  // For your default = true
    };
    
    int main() {
        A s;
        s[A_index<false>{1}];
    
        using t = A_index<true>;
        s[t{0}];
    }
    

    或者您可以拥有一个具有A&amp; 引用的辅助模板结构,其中该结构具有模板参数:

    struct A {
    };
    
    template<bool s = true>
    struct A_index {
        A& a;
    
        auto operator[](int i) { }
    };
    
    int main() {
      A s;
      A_index<false> view{ s };
      view[1];
    }
    

    或者您可以只使用非运算符成员函数。

    【讨论】:

    • 谢谢!我喜欢标签调度的想法,如果要推导其他模板参数并且因此默认模板参数将是一个问题,这将特别有用。但是,我现在将问题悬而未决,因为问题更多地指向在函数调用中指定模板参数的不同方式(如果存在)。
    猜你喜欢
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多