C++重载运算符 ()

huangapple go评论68阅读模式
英文:

C++ operator () overloading

问题

这段代码是一个结构体 EnumClass,它包含了一个模板化的成员函数 operator(),该函数接受一个参数 T t,并将其强制转换为 std::size_t 类型后返回。这个结构体似乎用于将不同类型的值转换为 std::size_t 类型的哈希值或索引值。

英文:

Could anybody explain what this code does?

struct EnumClass
    {
        template <typename T>
        std::size_t operator()(T t) const
        {
            return static_cast<std::size_t>(t);
        }
    };

答案1

得分: 6

它为类型为EnumClass的任何对象定义了运算符(),接受任何类型的一个参数。该运算符的结果为该参数,强制转换为size_t类型。

EnumClass e;
e(1); // 评估为(size_t)1

当然,这几乎是毫无意义的。(在某些其他上下文中,它可能有某种意义,但独立和原样,它没有意义 - 您不需要一个EnumClass对象来将某物强制转换为size_t。)

英文:

It defines the operator () for any object of type EnumClass, taking one argument of any type. The operator evaluates to that argument, cast to type size_t.

EnumClass e;
e(1); // evaluates to (size_t)1

This is borderline nonsense, of course. (It might make sense in some other context, but stand-alone and as-is, it doesn't -- you don't need an EnumClass object to cast something to size_t.)

huangapple
  • 本文由 发表于 2020年1月6日 16:27:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/59608836.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定