c++ - 模板中的隐式转换和编译器强制

标签 c++ templates operator-overloading

我有这个非常简单的包装器模板:

template<class T>
struct wrapper {
    inline operator T () {
        return v;
    }

    inline wrapper(T v):v(v) { }

    T v;
};

尝试将它与任何非原始类型一起使用(例如)依赖于定义它的模板的比较运算符看起来没有希望:

std::string t = "test";
assert(t == t);

typedef wrapper<std::string> string_wrapper;
assert(string_wrapper(t) == string_wrapper(t));

GCC 4.4.5 提示这个错误:

error: no match for ‘operator==’ in ‘wrapper<std::basic_string<char> >(std::basic_string<char>(((const std::basic_string<char>&)((const std::basic_string<char>*)(& t))))) == wrapper<std::basic_string<char> >(std::basic_string<char>(((const std::basic_string<char>&)((const std::basic_string<char>*)(& t)))))’

有趣的是,GCC 三重转换模板,然后无法使用为 std::string 定义的 operator ==

我不认为隐式强制转换是不可能的,因为如果我将 std::string 更改为 intdoublebool 或任何原始类型,GCC 将选择正确的运算符。

我不想为 wrapper 结构定义 operator ==,因为那个操作符只是一个例子,我需要 wrapper 来“感觉”就像关于运算符的真实类型。

只是在转换中 GCC 误解了我的语法,如果我创建一个包装器并尝试将它与自身进行比较,GCC 再次提示(尽管没有三重转换)它找不到匹配的 == 运算符:

typedef wrapper<std::string> string_wrapper;
string_wrapper tw(t);
assert(tw == tw);

error: no match for ‘operator==’ in ‘tw == tw’

wrapper 提供转换时,为什么 GCC 不能找到和/或使用 std::string operator == std::string

最佳答案

该运算符 T 称为“转换运算符”或“转换函数”,而不是强制转换。 “转换”是隐含的;转换是显式的。

编译器找不到 std::string 的运算符==,因为重载解析规则不允许这种情况发生。有关您真正尝试做的事情的更多详细信息可能有助于提供解决方案。

关于c++ - 模板中的隐式转换和编译器强制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5012084/

相关文章:

c++ - STL 是否包含适用于数组的迭代器?

c++ - 如何在 C++ 中创建 RAW TCP/IP 数据包?

templates - 谷歌计算引擎: How to change instance template

c++ - 如何在共享指针中为模板类使用前向声明(在 C++ 中)

c++ - C++中重载运算符的参数顺序

c++ - Boost 和 OpenCV 库与 Eclipse CDR 的静态链接。错误

C++:将对象添加到自定义向​​量类时程序崩溃

javascript - HTML 模板不适用于 For-In 循环 JavaScript

c++ - 如何选择 C++ 中的运算符重载?

c++ - 了解运算符重载和迭代器为什么会打印出 “wrhrwwr”?