c++ - 如何将模板类型的常量应用于另一种类型

标签 c++ templates

我想引用模板类内的值。模板化类可以是 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/

相关文章:

c++ - 如何在没有模板的情况下将左值传递给仅采用右值的函数

html - Meteor 模板强制为 HTML

c++ - 加权 boolean 值 - 缩放

c++ - 如何在 C++ 中创建数据类型未知的模板类

c++ - 无法调用继承的 protected 泛型类成员

c++ - 如何使用 POCO 使用 HTTP 基本身份验证进行 HTTP 发布?

templates - Backbone Marionette 模板缓存默认不使用?

c++ - 为什么在将 C 样式数组传递给需要 std::string 的方法时出现链接器问题?

c++ - WinINet InternetGetProxyInfo : error 1003 ERROR_CAN_NOT_COMPLETE

c++ - 根据 2 个参数对 vector 进行排序