模板类型之间的隐式转换

Ant*_*ier 5 c++ templates

我创建了两种类型:bool_t并且number_t我想将一个转换为另一个(以两种方式).但是,我有一些问题要转换bool_tnumber_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>{};   
}
Run Code Online (Sandbox Code Playgroud)

而错误是:

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.
Run Code Online (Sandbox Code Playgroud)

如何解决这个问题呢?

asc*_*ler 3

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

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.
}
Run Code Online (Sandbox Code Playgroud)

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

#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>{};   
}
Run Code Online (Sandbox Code Playgroud)

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