相关疑难解决方法(0)

关于C++ 0x引用崩溃的问题

我不知道为什么这些代码无法编译.我在Visual c + + 2010和gcc中测试了-std = c ++ 0x.有人提出一些建议吗?谢谢!

template<typename T>
class Foo
{
public:
 void test(const T&){cout<<"const";}
 void test(      T&){cout<<"non const";}
};

int main()
{
 int a;
 Foo<int&> f;
}
Run Code Online (Sandbox Code Playgroud)

编译错误:'void Foo :: test(T)':已定义或声明的成员函数

但为什么这可以编译?

template<typename T> void foo(const T&){cout<<"const"; }
template<typename T> void foo( T&){cout<<"non const"; }
int main()
 {
    int a; 
    foo<int&>(a);
 }
Run Code Online (Sandbox Code Playgroud)

我读过c ++ 0x文章说:T && == T&,所以const T && == const T&?

c++ c++11

5
推荐指数
2
解决办法
845
查看次数

当 T 是引用类型时,为什么 const T&amp; 参数中的 const 会消失?

以下代码显示,如果const使用引用类型(例如,int&)实例化采用ref-to-参数的模板,则该参数不是const

#include <iostream>

template<typename T>
void f(const T& arg)         // arg isn't const if T is a reference type
{
  arg = -1;
}

int main()
{
  int x = 0;
  f<int&>(x);                // instantiate f with reference type
  std::cout << x << '\n';    // prints -1 under gcc, clang, and msvc
}
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?

我的猜测是,最初的类型argisint & const &并且它以某种方式转换为int&. 如果是这样,就标准而言,这究竟是如何发生的?如果这不是正在发生的事情,那是什么?

c++ templates type-deduction

5
推荐指数
1
解决办法
556
查看次数

C++:显式指定引用类型作为类型参数的模板函数

我在玩 C++ 模板类型推导并设法编译了这个小程序。

template<typename T>
 void f(const T& val)
 {
   val = 1;
 }


 int main()
 {
    int i = 0;
    f<int&>(i);
 }
Run Code Online (Sandbox Code Playgroud)

它可以在所有主要编译器上编译,但我不明白为什么。为什么可以f赋值val,什么时候val显式标记const?它是这些编译器中的错误还是根据 C++ 标准的有效行为?

c++ function-templates

3
推荐指数
1
解决办法
254
查看次数