强制操作符_(下划线)

Forcing operator_ (underscore)

本文关键字:下划线 操作符      更新时间:2023-10-16

这个问题是的乐趣,我知道我不能定义operator_

然而,我想真的想要"弯曲"这个规则,让下面的内容有效(有效是松散定义的!)

T result = somevar _ someother;

我没有一个可能的解决方案,但也许你可以,可能使用一些预处理器 bertricks。(当然,仅仅#define _ SOMETHING是相当危险的)

任何帮助都非常感谢!

这个怎么样:

#include <iostream>
struct Underscore {};
#define _ | Underscore() |
template<typename T>
struct Has
{
    const T& m_t;
    Has( const T& t )
    : m_t( t )
    {
    }
};
template<typename T>
Has<T> operator|( const T& lhs, const Underscore& )
{
    return Has<T>( lhs );
}
template<typename T, typename U>
auto operator|( const Has<T>& lhs, const U& rhs )
{
    std::cout << "This is the body of your iterator for " << lhs.m_t << " and " << rhs << std::endl;
    return 0;
}
int main()
{
    const std::string a = "a";
    const std::string b = "b";
    a _ b;
}

为了好玩,也许是这样的?

#include <iostream>

struct _magic_
{
};
template<class T>
  struct enchanted
  {
    enchanted(T t) : value(t) {}
    T value;
  };
static constexpr auto _ = _magic_{};
template<class T>
enchanted<T> operator| (T&& t, _magic_ magic)
{
  return {std::forward<T>(t)};
}
template<class T, class U>
auto operator| (const enchanted<T>& e, U u)
{
  return e.value + u;
}
int main()
{
  int x = 4;
  int y = 5;
  auto z = x |_| y;
  std::cout << z << std::endl;
}