Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何将constness从模板类型应用到其他类型_C++_Templates - Fatal编程技术网

C++ 如何将constness从模板类型应用到其他类型

C++ 如何将constness从模板类型应用到其他类型,c++,templates,C++,Templates,我想引用模板类中的值。模板类可以是常量或非常量,因此值引用需要反映这一点。在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 typenam

我想引用模板类中的值。模板类可以是常量或非常量,因此值引用需要反映这一点。在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 &'
}

在C++11中,使用std::remove_const可以非常简单:


您可以使用helper类来推断值类型是int&还是const int&

使用汽车怎么样

template<typename T>
void f(T & x) {
    auto &r = x.v;
}

抢手货我的例子并不完整。实际上,我需要在VC++2010中使用lambda声明no lambda autos的类型。我会在30秒内更新这个例子。谢谢这很有道理。我知道我以前见过这种情况,但我似乎记不起这些技术,在本例中,使用模板类生成另一种类型。谢谢。这对我来说已经足够解决这个问题了@奥尔普给了我确切的答案,所以我给了他重点,但非常感谢你的帮助。
class X
{
   public:
      typedef int value_type;
      value_type v;
};

template <typename T> struct reference_type;

template <> struct reference_type<X>
{
   using type = int&;
};

template <> struct reference_type<const X>
{
   using type = int const&;
};


template <typename T>
void f(T & x) {
   // needs constness of T applied to T::value_type
   typedef typename reference_type<T>::type value_ref;
   value_ref vr = 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;
}