mutableVoid
mutableVoid

Reputation: 1506

How to specify template arguments for templated operators

I've got a templated operator as class member:

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

I specify the template parameter in the following (rather cumersome) way:

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

This kind of destroys the 'beauty' of using an operator (aside from the fact that it is probably not a best practice to use templated operators; I use it in my code for having a conditionally const return type without re-implementing the logic and use the template only internally in the at implementation).

Is there a more condensed notation for specifying the template argument?

Upvotes: 1

Views: 156

Answers (1)

Artyer
Artyer

Reputation: 40791

You can wrap the passed parameter in a template class which you can deduce, kind of like tag dispatching:

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}];
}

Or you can have a helper template struct that has an A& reference where the struct has the template parameters:

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];
}

Or you could just use non-operator member functions.

Upvotes: 1

Related Questions