【问题标题】:template parameter with conversion operator带有转换运算符的模板参数
【发布时间】:2016-05-19 11:59:38
【问题描述】:
#include <iostream>

template <typename T1, typename T2> 
bool func(const T1& t, const T2& t2) {
    return t == t2;
}


class Base {
public:
    bool operator ==(const Base&) const { return true;}
    Base(int y) : x(y) {}
    operator int() {
        return x;
    }
    int x;
};

int main() {
    func<long, Base>(4L, Base(5)); // not ok
    func<long, long>(4L, Base(5)); //ok
}

谁能详细说明为什么第一个版本不起作用?也就是说,为什么func中的二元运算符==不使用转换运算符int将绑定到Base的模板参数转换为int?

有没有办法只通过修改类 Base 来使版本 1 工作?

【问题讨论】:

  • 注意:您有两个隐式转换(构造函数和运算符)。制作一个“显式”(可能是构造函数)以避免麻烦。

标签: c++ templates c++11 metaprogramming


【解决方案1】:

您的 func 通过 const 引用接受其参数,但在您的 Base 类中定义的 operator int() 是一个非常量成员函数。将其标记为 const 成员函数,如下所示,您的代码将编译:

#include <iostream>

template <typename T1, typename T2> 
bool func(const T1& t, const T2& t2) {
    return t == t2;
}


class Base {
public:
    bool operator ==(const Base&) const { return true;}
    Base(int y) : x(y) {}
    operator int() const {
        return x;
    }
    int x;
};

int main() {
    func<long, Base>(4L, Base(5)); // ok now!
    func<long, long>(4L, Base(5)); // ok
}

Live example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-22
    • 1970-01-01
    相关资源
    最近更新 更多