说有一个计算阶乘(n)的函数
factorial(7)是否为1到7中的每一个创建了7个函数对象
并在必要时使用这些值(对于阶乘(8)像阶乘(7)*8)
引自NM Jousttis的"The C++ Standard Library",第5.9节
#include < iostream>
#include < list>
#include < algorithm>
using namespace std;
//function object that adds the value with which it is initialized
class AddValue {
private:
int the Value; //the value to add
public:
//constructor initializes the value to add
AddValue(int v) : theValue(v) { }
//the "function call" for the element adds the value
void operator() (int& elem) const { elem += theValue; }
};
int main()
{
list<int> coll;
for (int i=1; …Run Code Online (Sandbox Code Playgroud) 我在维基百科上找到了这段代码
class compare_class {
public:
bool operator()(int A, int B) const {
return A < B;
}
};
...
// Declaration of C++ sorting function.
template <class ComparisonFunctor>
void sort_ints(int* begin_items, int num_items, ComparisonFunctor c);
...
int main() {
int items[] = {4, 3, 1, 2};
compare_class functor;
sort_ints(items, sizeof(items)/sizeof(items[0]), functor);
}
Run Code Online (Sandbox Code Playgroud)
起初我想知道如果在sort_ints中提到了仿函数而没有任何括号,那么A和B参数如何传递给operator()(int A,int B).
然后我想到A和B被传递给sort_ints函数内的函数对象.但那么,sort_ints的声明是否应该使用'ComparisonFunctor***c'而不是'ComparisonFunctor c',因为它接收函数的地址?
在sort_ints函数内部,函数调用函数是否会完成这样的操作?
functor(*begin_items, *(begin_items+1));
Run Code Online (Sandbox Code Playgroud) 拥有以下代码:
template<typename T, typename OutStream = std::ostream> struct print {
OutStream &operator()(T const &toPrint, OutStream &outStream = std::cout) const {
outStream << toPrint;
return outStream;
}
};
Run Code Online (Sandbox Code Playgroud)
这个电话是错误的:
print<int>(2);
Run Code Online (Sandbox Code Playgroud)
错误信息:
1>main.cpp(38): error C2440: '<function-style-cast>' : cannot convert from 'int' to 'print<T>'
1> with
1> [
1> T=int
1> ]
1> No constructor could take the source type, or constructor overload resolution was ambiguous
Run Code Online (Sandbox Code Playgroud)
这个电话没有错误:
print<int> intPrinter;
intPrinter(2);
Run Code Online (Sandbox Code Playgroud)
我可以在没有实例化的情况下以某种方式使用函数对象吗?我不能在这里使用模板功能,因为我需要部分专业化功能.
我应该如何将结构中的函数作为仿函数传递?我认为这应该工作正常,但它没有:
#include <algorithm>
using namespace std;
struct s {
int a[10];
bool cmp(int i, int j) {
// return something
}
void init() {
sort(a, a + 10, cmp);
}
};
Run Code Online (Sandbox Code Playgroud)
得到了 <unresolved overloaded function type>
我在Visual Studio 2012中使用函数对象时遇到问题.
我创建了一个简单的std::vector,添加了ints0-9并希望使用函数对象创建它的总和.我的班级定义(内联):
template <class T>
class Sum {
private:
T val;
public:
Sum (T i = 0) : val(i) {
}
void operator()(T x) {
val += x;
}
T result() const {
return val;
}
~Sum() {
std::cout << "Invoked destructor! val: " << val << " for this: " << this << std::endl;
}
};
Run Code Online (Sandbox Code Playgroud)
我的主要功能:
int main(int argc, char *argv[]){
Sum<int> s;
int contents[] = {1,2,3,4,5,6,7,8,9};
std::vector<int> vec = std::vector<int>(contents, contents …Run Code Online (Sandbox Code Playgroud) 假设我有这个类(继承自std :: Vector,它只是一个例子)
#include <vector>
using namespace std;
template <class T>
class C : public vector<T> {
// I don't want to use static keyword
void transformation(T i) {
i *= 100;
}
public:
void method() {
for_each(this->begin(), this->end(), transformation);
}
};
int main() {
C<double> c;
for (int i=-3; i<4; ++i) {
c.push_back(i);
}
c.method();
}
Run Code Online (Sandbox Code Playgroud)
如何在类本身内部使用类方法调用for_each?我知道我可以使用static关键字,但是有什么其他方法可以在不使用静态的情况下使用函数对象?
我在编译时收到此错误消息:
for_each.cc:21:55:错误:无法将'C :: transformation'从类型'void(C ::)(double)'转换为'void(C ::*)(double)'for_each(this-> begin(),this-> end(),transformation);
我想我需要添加.*或在->*某处,但我找不到在哪里以及为什么.
template<class Key, class Value>
AVLTree<Key,Value>::AVLTree(){
this->lessThan = Key::operator<;
}
Run Code Online (Sandbox Code Playgroud)
此代码应该使std::function<bool(Key, Key)> lessThan字段默认等于键的<运算符.但是,当我尝试这个时AVLTree<int,int>,我得到:
error: ‘operator<’ is not a member of ‘int’
Run Code Online (Sandbox Code Playgroud)
我是格式化这个错误,还是在C++中这是不可能的?
我正在从cppreference中读取代码示例:
#include <functional>
#include <queue>
#include <vector>
#include <iostream>
template<typename T> void print_queue(T& q) {
while(!q.empty()) {
std::cout << q.top() << " ";
q.pop();
}
std::cout << '\n';
}
int main() {
std::priority_queue<int> q;
for(int n : {1,8,5,6,3,4,0,9,7,2})
q.push(n);
print_queue(q);
std::priority_queue<int, std::vector<int>, std::greater<int> > q2;
for(int n : {1,8,5,6,3,4,0,9,7,2})
q2.push(n);
print_queue(q2);
// Using lambda to compare elements.
auto cmp = [](int left, int right) { return (left ^ 1) < (right ^ 1);};
std::priority_queue<int, std::vector<int>, decltype(cmp)> q3(cmp);
for(int …Run Code Online (Sandbox Code Playgroud) 我有这个声明
struct Z {
void operator ()( int a ) {
cout << "operator()() " << a << endl;
}
};
Z oz, *zp = &oz;
oz(1); //ok
(*zp)(2); //ok
zp(3); //"error: 'zp' cannot be used as a function"
Run Code Online (Sandbox Code Playgroud)
有没有办法修改结构声明,所以调用3号会成功吗?
我正在尝试创建一个Func表示函数的类,然后创建一个Dot组成函数的数据类型.下面是我的尝试,但我收到编译错误:
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE GADTs #-}
module Func where
class Func f a b | f -> a, f -> b where
apply :: f -> a -> b
data Dot f1 f2 where
Dot :: (Func f1 a b, Func f2 b c) => f1 -> f2 -> Dot f1 f2
instance Func (Dot f1 f2) a c where
apply …Run Code Online (Sandbox Code Playgroud) 我知道这std::function是用类型擦除惯用法实现的。类型擦除是一种方便的技术,但它的缺点是它需要在堆上存储底层对象的寄存器(某种数组)。
因此,当创建或复制function对象时,需要进行分配,因此该过程应该比简单地将函数作为模板类型进行操作要慢。
为了检查这个假设,我运行了一个测试函数,该函数累积n = cycles连续的整数,然后将总和除以增量数n。首先编码为模板:
#include <iostream>
#include <functional>
#include <chrono>
using std::cout;
using std::function;
using std::chrono::system_clock;
using std::chrono::duration_cast;
using std::chrono::milliseconds;
double computeMean(const double start, const int cycles) {
double tmp(start);
for (int i = 0; i < cycles; ++i) {
tmp += i;
}
return tmp / cycles;
}
template<class T>
double operate(const double a, const int b, T myFunc) {
return myFunc(a, b);
}
Run Code Online (Sandbox Code Playgroud)
和main.cpp:
int …Run Code Online (Sandbox Code Playgroud)