模板类型之间不能 convert/cast(无法推导模板参数)

Can't convert/cast between template types ( couldn’t deduce template parameter )

在摆弄模板和 static_assert 时,我遇到了以下问题

(下面是一个简化的例子问题是一样的)


template< size_t n >
struct W {
    class X {
        public:
            /* breaks normal constructor
            template< size_t o >
            X( typename W<o>::X & y ){
                static_assert( o < n , "bad");
            };
            */

            template< size_t m >
            operator typename W<m>::X() const { 
                static_assert( n < m , "bad");
                return W<m>::X();
            };
    };
};

void func( W<6>::X y ){}

int main() {
    W<5>::X x;

    // > error: conversion from ‘X<5>’ to non-scalar type ‘X<6>’ requested
    //W<6>::X y = x; 

    // > error: error: no matching function for call to ‘W<5>::X::operator W<6>::X()
    // > note:   template argument deduction/substitution failed:
    // > note:   couldn’t deduce template parameter ‘m’
    //x.operator W<6>::X();

    // >  error: no matching function for call to ‘W<6>::X::X(W<5>::X&)’
    // > note:   template argument deduction/substitution failed:
    // > note:   couldn’t deduce template parameter ‘o’
    //static_cast< W<6>::X >(x);
    // similarly
    //( W<6>::X ) x;

    // End Goal:
    // > error: could not convert ‘x’ from ‘X<5>’ to ‘X<6>’
    func( x );
}

简单地说,我希望仅当 n < m.

时才能 cast/convert W<n>::X 对象到 W<m>::X 对象

一些补充说明

潜在的问题是,在嵌套类型中无法推导模板参数。如果您提供辅助变量(在我的示例中为 N )并为转换运算符使用更通用的模板,则可以解决该问题。如果需要,您可以使用 SFINAE 过滤掉其他类型 W<n>::X

开始吧:

template< size_t n >
struct W {
    class X {
        public:
            // helper to get template parameter because it can't be deduced
            static constexpr size_t N = n; 

            template < typename T, size_t x=T::N >
                operator T() const 
                {
                    //static_assert( x < n , "bad");
                    std::cout << "Target: " << n << " Source " << x << std::endl;
                    return T(); 
                }

            X()=default;
    };   
};


void func( W<6>::X  ){}  

int main() {
    W<5>::X x;
    W<6>::X y=x; 
    x.operator W<6>::X();
    static_cast< W<6>::X >(x);
    ( W<6>::X ) x; 
    func( x ); 
}