【问题标题】:Forcing operator_ (underscore) [closed]强制运算符_(下划线)[关闭]
【发布时间】:2016-11-02 06:25:21
【问题描述】:

这个问题是为了好玩,我知道我不能定义operator_

但是,我真的想“改变”这条规则,将以下内容视为有效(valid 定义松散!)。

T result = somevar _ someother;

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

非常感谢任何帮助!

【问题讨论】:

  • 出于兴趣,你想让这个“操作员”做什么?
  • 你已经给出了答案,直接使用#define _ OPERATOR_OF_YOUR_CHOICE,但它有什么乐趣呢?恕我直言,宏和混淆代码都不好玩
  • @RichardHodges 什么,返回另一个具有不同内容的T,我现在没有具体的想法。以class T { public: int content; };为例。
  • @tobi303 有趣的是尽量避免#define,如果可能的话。是的,我发现混淆很有趣! :)
  • @nwp 好吧,玩得开心与否仍然是一个公开辩论...stackoverflow.com/questions/5508110/…

标签: c++ c++11 operator-overloading c++14


【解决方案1】:

这个怎么样:

#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;

}

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 为自定义类型定义魔术怎么样?
    • @senseiwa 只提供template&lt;class T, class U&gt; auto operator| (const enchanted&lt;T&gt;&amp; e, U u)的专业化
    猜你喜欢
    • 1970-01-01
    • 2011-08-24
    • 2023-04-01
    • 2021-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-15
    相关资源
    最近更新 更多