c++ - 如何对成员函数使用隐式类型转换?

标签 c++

让我们考虑以下示例,了解隐式类型转换有效无效的情况:

#include <iostream>
#include <vector>

struct Thingy
{
    void write()
    {
        std::cout << "x" << std::endl;
    }
};

struct Node
{
    Thingy a;
    int data;
    operator Thingy&(){return a;}
};

void f(Thingy thingy)
{
    thingy.write();
}

template <typename TIterator>
void f (TIterator begin, TIterator end)
{
    for (TIterator it = begin; it != end; ++it)
        it->write();
}

int main()
{
    std::vector<Node> vector(10);

    f(vector.begin(), vector.end());  // Doesn't compile
    f(vector[3]);                     // compiles
    vector[3].write();                // Doesn't compile
    return 0;
}

为什么会这样?

void Node::write(); 

不应从根本上不同于:

void write(Node* this);

有没有办法让我的示例代码编译运行?

编辑:

我了解为什么它不起作用的机制,我想了解其中的哲学。为什么 C++ 标准委员会认为这是一个坏主意?

最佳答案

它不起作用,因为你在做的时候从不要求编译器进行转换:

it->write();

我想它应该与 static_cast 一起工作:

static_cast<Thingy&>(*it).write();

但我不太确定你应该简单地使用:

it->get_a().write();

或者更好,正如其他人所说,声明一个用 Node 编写的方法。

隐式转换可能是邪恶的。

因为你不能改变 f 函数,你应该只包装迭代器,这样它就可以取消引用一个 Thingy 而不是一个节点,如果你可以使用 Boost :

#include <iostream>
#include <vector>
#include <boost/iterator/transform_iterator.hpp>
struct Thingy
{
    void write()
    {
        std::cout << "x" << std::endl;
    }
};

struct Node
{
    Thingy a;
    int data;
    operator Thingy&(){return a;}
};

void f(Thingy thingy)
{
    thingy.write();
}

template <typename TIterator>
void f (TIterator begin, TIterator end)
{
    for (TIterator it = begin; it != end; ++it)
        it->write();
}

struct Node2Thingy
{
  typedef Thingy& result_type;
  Thingy& operator()(Node& n) const { return n.a; }
};

int main()
{
    std::vector<Node> vector(10);

    f(boost::make_transform_iterator(vector.begin(), Node2Thingy()),
         boost::make_transform_iterator(vector.end(), Node2Thingy()));
    f(vector[3]);                     // compiles


    return 0;
}

在 g++ 4.8.1 上工作(但肯定也在旧版本上)。

您试图通过添加“隐式”间接寻址来解决您的问题,但在那种情况下,它不起作用。您可以通过添加显式间接寻址来解决它。

要回答您的问题,幕后没有哲学。它纯粹是机械的,C++ 使用在编译时解析的类型,因此所有内容在执行时间之前都有其类型。您希望编译器如何猜测必须在 Node 上调用转换运算符。

关于c++ - 如何对成员函数使用隐式类型转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18172802/

相关文章:

java - JNI :how to call c++ function from Java Native Method

c++ - 模板化运算符的奇怪行为<<

c++ - C++ 中有没有什么方法可以在既不调用函数模板也不提供其模板参数的情况下引用函数模板?

c++ - 通过网络测量耗时

c++ - 我应该从包装函数中获得多少开销

c++ - libdmtx 死了吗,建议更换?

C++调用父函数仅在使用指针时有效

c++ - 返回不同类型的变量

c++ - 我如何#include 一个名称由宏构建的文件?

c++ - 如何迭代 CString 并将其字符与 int 进行比较?