在Stack Overflow问题中,在C++ 11中不允许重新定义lambda,为什么?,给出了一个不编译的小程序:
int main() {
auto test = []{};
test = []{};
}
Run Code Online (Sandbox Code Playgroud)
问题得到了回答,一切似乎都很好.然后是Johannes Schaub并做了一个有趣的观察:
如果你
+
在第一个lambda之前放置一个,它会神奇地开始工作.
所以我很好奇:为什么以下工作呢?
int main() {
auto test = +[]{}; // Note the unary operator + before the lambda
test = []{};
}
Run Code Online (Sandbox Code Playgroud)
我有一个模板 class A
template <unsigned int m>
class A
{
public:
A(int) {}
};
Run Code Online (Sandbox Code Playgroud)
哪个有构造函数int
.我有一个手术:
template<unsigned int m>
A<m> operator+(const A<m>&, const A<m>&)
{
return A<m>(0);
}
Run Code Online (Sandbox Code Playgroud)
但是当我打电话时:
A<3> a(4);
A<3> b = a + 5;
A<3> c = 5 + a;
Run Code Online (Sandbox Code Playgroud)
我想int
隐式转换为A,但编译器会抛出错误.
有没有优雅的方法来启用隐式转换而不使用以下解决方案:
a + A<m>(5)
operator+<3>(a, 5)
我正在学习C++,我正在尝试实现一个二进制搜索函数,它找到谓词所在的第一个元素.函数的第一个参数是向量,第二个参数是一个计算给定元素的谓词的函数.二进制搜索功能如下所示:
template <typename T> int binsearch(const std::vector<T> &ts, bool (*predicate)(T)) {
...
}
Run Code Online (Sandbox Code Playgroud)
如果像这样使用,这可以按预期工作:
bool gte(int x) {
return x >= 5;
}
int main(int argc, char** argv) {
std::vector<int> a = {1, 2, 3};
binsearch(a, gte);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我使用lambda函数作为谓词,我会收到编译器错误:
search-for-a-range.cpp:20:5: error: no matching function for call to 'binsearch'
binsearch(a, [](int e) -> bool { return e >= 5; });
^~~~~~~~~
search-for-a-range.cpp:6:27: note: candidate template ignored: could not match 'bool (*)(T)' against '(lambda at
search-for-a-range.cpp:20:18)'
template <typename T> int …
Run Code Online (Sandbox Code Playgroud) 在下面的代码中,我想通过隐式转换int
为Scalar<int>
对象来调用模板函数.
#include<iostream>
using namespace std;
template<typename Dtype>
class Scalar{
public:
Scalar(Dtype v) : value_(v){}
private:
Dtype value_;
};
template<typename Dtype>
void func(int a, Scalar<Dtype> b){
cout << "ok" <<endl;
}
int main(){
int a = 1;
func(a, 2);
//int b = 2;
//func(a, b);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为什么模板参数推导/替换失败?评论代码也是错误的.
test.cpp: In function ‘int main()’:
test.cpp:19:12: error: no matching function for call to ‘func(int&, int)’
func(a, 2);
^
test.cpp:19:12: note: candidate is:
test.cpp:13:6: note: template<class Dtype> void func(int, …
Run Code Online (Sandbox Code Playgroud) 我问的最后一个问题是我在试图理解另一件事时偶然发现的事情......我也无法理解(不是我的一天).
这是一个很长的问题陈述,但至少我希望这个问题可能对许多人有用,而不仅仅是我.
我的代码如下:
template <typename T> class V;
template <typename T> class S;
template <typename T>
class V
{
public:
T x;
explicit V(const T & _x)
:x(_x){}
V(const S<T> & s)
:x(s.x){}
};
template <typename T>
class S
{
public:
T &x;
explicit S(V<T> & v)
:x(v.x)
{}
};
template <typename T>
V<T> operator+(const V<T> & a, const V<T> & b)
{
return V<T>(a.x + b.x);
}
int main()
{
V<float> a(1);
V<float> b(2);
S<float> c( b );
b …
Run Code Online (Sandbox Code Playgroud)