带转换运算符的模板参数

时间:2016-05-19 11:59:39

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

#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工作吗?

1 个答案:

答案 0 :(得分:3)

您的func通过const引用接受其参数,但operator int()类中定义的Base是非const成员函数。将其标记为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