在摆弄模板和 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 );
}
简单地说,我希望能够转换/转换 W<n>::X
反对 W<m>::X
仅当 n < m
时才对象.
一些补充说明
- 我无法使用
X<n>
形式的类而不是W<n>::X
-
W::X<n>
的构造函数将是私有(private)的
最佳答案
根本问题是,在嵌套类型中,无法推导模板参数。如果您提供一个辅助变量(在我的示例中为 N )并为转换运算符使用更通用的模板,则可以解决该问题。您可以过滤掉其他类型,如 W<n>::X
如果需要,请与 SFINAE 合作。
我们开始:
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 );
}
关于c++ - 无法在模板类型之间进行转换/转换(无法推断模板参数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71793094/