gpt4 book ai didi

c++ - 模板类型之间的隐式转换

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:27:38 25 4
gpt4 key购买 nike

我创建了两种类型:bool_tnumber_t 我想将一种转换为另一种(以两种方式)。但是,我在将 bool_t 转换为 number_t 时遇到了一些问题。

基本上我想做的是(但它不编译):

template<bool v>
struct bool_t {
template<template<int> typename T>
operator T<v ? 1 : 0>() {
return {};
}
};

template<int N>
struct number_t {
template<int n1, int n2>
friend number_t<n1 + n2> operator+(number_t<n1>, number_t<n2>) {
return {};
}
};


int main() {
number_t<0>{} + bool_t<0>{};
}

错误是:

prog.cc:19:19: error: invalid operands to binary expression ('number_t<0>' and 'bool_t<0>')
number_t<0>{} + bool_t<0>{};
~~~~~~~~~~~~~ ^ ~~~~~~~~~~~
prog.cc:12:26: note: candidate template ignored: could not match 'number_t' against 'bool_t'
friend number_t<n1 + n2> operator+(number_t<n1>, number_t<n2>) {
^
1 error generated.

如何解决这个问题?

最佳答案

在尝试将函数参数类型与函数参数类型匹配以进行模板参数推导时,从不考虑用户定义的转换。所以这个问题是这种错误的更复杂的版本:

template <int> struct X {};
struct Y {
operator X<2> () const { return {}; }
};
template <int N>
void f(X<N>) {}

int main()
{
Y y;
f(y); // Error: Cannot deduce template argument.
}

因为看起来您正在按照模板元编程库的方式制作某些东西,也许您可​​以定义一个自定义机制来将您的库中的类型“转换为模板”?

#include <type_traits>

template<bool v>
struct bool_t {
// (Add some appropriate SFINAE.)
template<template<int> typename T>
constexpr T<v ? 1 : 0> convert_template() const {
return {};
}
};

template<typename T, template<int> class TT>
struct type_specializes : std::false_type {};

template<template<int> class TT, int N>
struct type_specializes<TT<N>, TT> : std::true_type {};

template<int N>
struct number_t {
// Allow "conversion" to my own template:
template<template<int> typename T>
constexpr std::enable_if_t<type_specializes<number_t, T>::value, number_t>
convert_template() const { return {}; }

private:
// Used only in decltype; no definition needed.
template<int n1, int n2>
static number_t<n1 + n2> sum_impl(number_t<n1>, number_t<n2>);

template<typename T1, typename T2>
friend auto operator+(T1&& x, T2&& y)
-> decltype(number_t::sum_impl(
x.template convert_template<number_t>(),
y.template convert_template<number_t>()))
{ return {}; }
};

int main() {
number_t<0>{} + bool_t<0>{};
}

如果你想让两个操作数都是 bool_t 特化,operator+ 将需要是一个适当的可见命名空间成员;如果合适,您可以向其中添加更多 SFINAE 检查。

关于c++ - 模板类型之间的隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54601580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com