如何使用模板函数进行隐式转换 [英] How to use template function for implicit conversion

查看:60
本文介绍了如何使用模板函数进行隐式转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

非常简化的例子(不用管A类和操作符在做什么,只是举例):

Very simplified example (nevermind what the class A and operators are doing, it's just for example):

#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==(具有相同的主体):

But if I replace two operator=='s (with same body) with template:

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 用户定义模板推导指南吗?或者其他什么?

Is it possible to use template here? Can I use C++17 user-defined template deduction guides somehow? Or anything else?

推荐答案

另一个选择是 friend 函数,所以函数不是模板,而是使用模板参数:

Another alternative is friend function, so the function is not template, but use the template argument:

template <bool is_signed>
class A {
public:
    // implicit conversion from int
    A(int a) : a_{is_signed ? -a : a}
    {}

    int a_;

    friend bool operator==(const A& lhs, const A& rhs) {
        return lhs.a_ == rhs.a_;
    }
};

演示

这篇关于如何使用模板函数进行隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆