相关疑难解决方法(0)

防止非常量左值解析为右值引用而不是const左值引用

我无法通过const引用重载函数来获取值,或者如果它是rvalue则是rvalue引用.问题是我的非const左值绑定到函数的右值版本.我在VC2010中这样做.

#include <iostream>
#include <vector>

using namespace std;

template <class T>
void foo(const T& t)
{cout << "void foo(const T&)" << endl;}

template <class T>
void foo(T&& t)
{cout << "void foo(T&&)" << endl;}

int main()
{
    vector<int> x;
    foo(x); // void foo(T&&) ?????
    foo(vector<int>()); // void foo(T&&)
}
Run Code Online (Sandbox Code Playgroud)

优先级似乎是推导foo(x)为

foo< vector<int> & >(vector<int>& && t)
Run Code Online (Sandbox Code Playgroud)

代替

foo< vector<int> >(const vector<int>& t)
Run Code Online (Sandbox Code Playgroud)

我尝试用r替换rvalue-reference版本

void foo(typename remove_reference<T>::type&& t)
Run Code Online (Sandbox Code Playgroud)

但这只会导致所有内容都解析为const-lvalue引用版本.

我该如何防止这种行为?为什么这仍然是默认值 - 考虑到允许修改rvalue-references似乎很危险,这给我留下了意外修改的局部变量.

编辑:刚添加了非模板版本的函数,它们按预期工作.将函数设为模板会更改重载决策规则吗?那真是令人沮丧!

void bar(const vector<int>& t)
{cout << "void bar(const …
Run Code Online (Sandbox Code Playgroud)

c++ templates metaprogramming rvalue-reference

19
推荐指数
2
解决办法
1902
查看次数

是否有可能合法地重载字符串文字和const char*?

在C++ 11中是否有可能重载const char*和字符串文字(const char[])?我们的想法是避免在strlen已知此长度时调用以查找字符串长度.

这个片段打破了G ++ 4.8和Clang ++ 3.2:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

template<typename T, int N>
void length(const T(&data)[N]) {
  printf("%u[]\n", N - 1);
}

template<typename T>
void length(const T* data) {
  printf("*%u\n", (unsigned)strlen(data));
}

int main() {
  length("hello");
  const char* p = "hello";
  length(p);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

错误(Clang):

test2.cpp:16:3: error: call to 'length' is ambiguous
  length("hello");
  ^~~~~~
test2.cpp:6:6: note: candidate function [with T = char, N = 6]
void length(const …
Run Code Online (Sandbox Code Playgroud)

c++ templates overloading c++11

14
推荐指数
1
解决办法
1386
查看次数