【发布时间】:2019-10-22 15:55:03
【问题描述】:
非常简化示例(不管A 类和操作员在做什么,这只是示例):
#include <iostream>
using namespace std;
template <bool is_signed>
class A {
public:
// implicit conversion from int
A(int a) : a_{is_signed ? -a : a}
{}
int a_;
};
bool operator==(A<true> lhs, A<true> rhs) {
return lhs.a_ == rhs.a_;
}
bool operator==(A<false> lhs, A<false> rhs) {
return lhs.a_ == rhs.a_;
}
int main() {
A<true> a1{123};
A<false> a2{123};
cout << (a1 == 123) << endl;
cout << (a2 == 123) << endl;
return 0;
}
这行得通。
但是如果我用模板替换两个operator==(具有相同的正文):
template <bool is_signed>
bool operator==(A<is_signed> lhs, A<is_signed> rhs) {
return lhs.a_ == rhs.a_;
}
,它的编译产生错误:
prog.cpp: In function ‘int main()’:
prog.cpp:31:14: error: no match for ‘operator==’ (operand types are ‘A<true>’ and ‘int’)
cout << (a1 == 123) << endl;
~~~^~~~~~
prog.cpp:23:6: note: candidate: ‘template<bool is_signed> bool operator==(A<is_signed>, A<is_signed>)’
bool operator==(A<is_signed> lhs, A<is_signed> rhs) {
^~~~~~~~
prog.cpp:23:6: note: template argument deduction/substitution failed:
prog.cpp:31:17: note: mismatched types ‘A<is_signed>’ and ‘int’
cout << (a1 == 123) << endl;
^~~
这里可以使用模板吗?我可以以某种方式使用 C++17 用户定义的模板推导指南吗?还是别的什么?
【问题讨论】:
标签: c++ templates implicit-conversion template-argument-deduction