vector<int> function(vector<int> &arr)
{
for(auto i = arr.size() - 1; i >= 0; i--)
std::cout << arr[i] << " ";
return arr;
}
int main()
{
vector<int> arr{1,2,3,4};
function(arr);
}
Run Code Online (Sandbox Code Playgroud)
为什么上面的程序会循环?如果我改变auto与int一切正常
我试图弄清楚 sfinae 概念在 C++ 中是如何工作的。但我无法说服对象类型编译器 if boolis trueor false。
#include <iostream>
class A {
public:
void foo() { std::cout << "a\n"; }
};
class B {
public:
void ioo() { std::cout << "b\n"; }
};
template<class T>
void f(const T& ob, bool value = false)
{
if constexpr (!value) ob.foo();
else ob.ioo();
}
int main()
{
A ob1;
B ob2;
f(ob1, true);
f(ob2, false);
}
Run Code Online (Sandbox Code Playgroud) 我有类似的情况,但更复杂。我试图在普通函数中调用模板函数,但无法编译...
#include <iostream>
using namespace std;
template<class T>
void ioo(T& x) { std::cout << x << "\n"; }
template<class T, class ReadFunc>
void f(T&& param, ReadFunc func) {
func(param);
}
int main() {
int x = 1;
std::string y = "something";
f(x, &::ioo);
}
Run Code Online (Sandbox Code Playgroud) //parameter pack sum example
constexpr int sum(int N= 0)
{
return N;
}
template<typename ...Args>
constexpr int sum(int first, int second, Args ...N)
{
return first + second + sum(N...);
}
int main()
{
std::cout << sum<int>(1,6,3);
}
Run Code Online (Sandbox Code Playgroud)
是否有可能在编译时通过std::initializer_list<int>我如何递归迭代来计算这个总和。
我有一个接收模板参数的函数。
template<class Container>
void function(const Container& object)
{
//here i want to iterate through object and print them
}
int main()
{
function(std::vector<int>{1,3,6,7});
function(std::vector<std::vector<int>>{{1,2,3},{2,5,7}});
}
Run Code Online (Sandbox Code Playgroud)
是否可以在一个函数中执行此操作?假设容器参数是整数。
有什么区别constexpr和consteval?
consteval int x1 = 2;
constexpr int x2 = 5;
Run Code Online (Sandbox Code Playgroud)
使用 constexpr 比使用 consteval 更好吗?