我想引用模板类内的值。模板化类可以是 const 或非常量,因此值引用需要反射(reflect)这一点。在 f() 中,如何将 T 的常量应用于 value_ref 声明?
class X
{
public:
typedef int value_type;
value_type v;
};
template<typename T>
void f(T & x) {
// needs constness of T applied to T::value_type
typedef typename T::value_type & value_ref;
auto lambda = [](value_ref v){}; // can't use auto in MSVC2010
lambda(x.v);
}
void g() {
X x;
X & r = x;
f(r); // works
X const & cr = x;
f(cr); // error: cannot convert from 'const X::value_type' to 'value_type &'
}
最佳答案
使用自动怎么样?
template<typename T>
void f(T & x) {
auto &r = x.v;
}
关于c++ - 如何将模板类型的常量应用于另一种类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34143115/