gpt4 book ai didi

c++ - 如何在模板结构中使用包装的 typedef 修复 C++ 编译

转载 作者:行者123 更新时间:2023-11-30 02:57:45 24 4
gpt4 key购买 nike

此代码将失败并显示错误消息(行号已关闭)。我该如何解决这个问题(保持相同的意图)?

g++ -o c_test c_test.cpp

c_test.cpp: 在函数 'int main(int, char**)' 中:

c_test.cpp:28:18: 错误:没有匹配函数来调用 'wcalc(CWrapped<5>::u_type&)'

c_test.cpp:28:18:注意:候选人是:

c_test.cpp:17:58: 注意:template int wcalc(typename CWrapped::u_type)

包装类型被传递给“calc”和“wcalc”函数,但第二个失败。我希望能够包装类型,这样我就可以使用编译时定义来指定不同的类型,但仍然使用相同的包装函数

// Example template class
template <int T_B>
class m_int {
public:
int x;
m_int() { x = T_B; }
int to_int() { return(x); }
};

// Desired Typedef wrap
template <int T_BITS> struct CWrapped {
typedef m_int<T_BITS> u_type;
};


// This is ok, no wrapping
template <int T_BITS> int calc(m_int<T_BITS> x) {
return(x.to_int());
}
// This fails when instantiated
template <int T> int wcalc(typename CWrapped<T>::u_type x) {
return(x.to_int());
}


int main(int argc, char* argv[]) {
CWrapped<5>::u_type s;

int x = calc(s);
int y = wcalc(s);
return(0);
}

最佳答案

来自 C++11 标准,第 14.8.2.5/16 段

“如果在带有非类型模板参数的函数模板的声明中,非类型模板参数用于函数参数列表中的子表达式,则该表达式是一个非-推导上下文如上文所述。示例:“

template <int i> class A { / ... / };
template <int i> void g(A<i+1>);
template <int i> void f(A<i>, A<i+1>);
void k() {
A<1> a1;
A<2> a2;
g(a1); // error: deduction fails for expression i+1
g<0>(a1); // OK
f(a1, a2); // OK
}

“注意:如果模板参数仅在非推导上下文中使用,则它们不参与模板参数推导。例如:”

template<int i, typename T> 
T deduce(typename A<T>::X x, // T is not deduced hereT t, // but T is deduced here
typename B<i>::Y y); // i is not deduced here
A<int> a;
B<77> b;
int x = deduce<77>(a.xm, 62, b.ym);
// T is deduced to be int, a.xm must be convertible to
// A<int>::X
// i is explicitly specified to be 77, b.ym must be convertible
// to B<77>::Y

由于上述原因,您的非类型模板参数 T 无法推导:您必须明确提供它:

int main(int argc, char* argv[]) {
CWrapped<5>::u_type s;

int x = calc(s);
int y = wcalc<5>(s); // Template argument 5 cannot be deduced!
return(0);
}

另请参阅此相关链接:C++, template argument can not be deduced (由@NateKohl 提供)

关于c++ - 如何在模板结构中使用包装的 typedef 修复 C++ 编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14224820/

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