這可能嗎?運營商作爲模板參數
template<operator Op> int Calc(int a, b)
{ return a Op b; }
int main()
{ cout << Calc<+>(5,3); }
如果沒有,是不是沒有ifs和開關來實現這一目標的方法?
這可能嗎?運營商作爲模板參數
template<operator Op> int Calc(int a, b)
{ return a Op b; }
int main()
{ cout << Calc<+>(5,3); }
如果沒有,是不是沒有ifs和開關來實現這一目標的方法?
你可以使用函子本:
template<typename Op> int Calc(int a, int b)
{
Op o;
return o(a, b);
}
Calc<std::plus<int>>(5, 3);
否 - 模板約類型或原始值。
可以nontheless通所謂函數對象,可以調用類似功能和攜帶所需的操作員的功能(儘管具有很好的語法)。
標準庫定義了幾個例如, std::plus
爲另外...
#include <functional>
template<typename Op>
int Calc(int a, int b, Op f) {
return f(a, b);
}
int main() {
cout << Calc(5,3, std::plus());
cout << Calc(5,3, std::minus());
}
爲此,您可以使用多態:
#include <cstdlib>
#include <iostream>
using namespace std;
class Operator
{
public:
virtual int operator()(int a, int b) const = 0;
};
class Add : public Operator
{
public:
int operator()(int a, int b) const
{
return a+b;
}
};
class Sub : public Operator
{
public:
int operator()(int a, int b) const
{
return a-b;
}
};
class Mul : public Operator
{
public:
int operator()(int a, int b) const
{
return a*b;
}
};
int main()
{
Add adder;
cout << adder(1,2) << endl;
Sub suber;
cout << suber(1,2) << endl;
Mul muler;
cout << muler(1,2) << endl;
return 0;
}
正確。但爲了證明這一點非常有用,您必須實際使用運行時多態並使用「操作符」和「接口」。爲這件事情實施'Calc'。然後提前+1! – Dario 2010-09-17 13:41:33
如果你指的全球運營商,你已經收到了一些答案。但在某些特定情況下,使用重載的操作符函數也可能會有所幫助。
這可能是微不足道的;儘管如此,它可能是在某些情況下有用這就是爲什麼我發佈了一個例子:
#include <iostream>
template<typename opType, typename T>
int operation(opType op, T a, T b)
{
return (a.*op)(1) + (b.*op)(1);
}
struct linear
{
int operator()(int n) const {return n;}
int operator[](int n) const {return n * 10;}
};
int main()
{
linear a, b;
std::cout << operation(&linear::operator(), a, b) << std::endl
<< operation(&linear::operator[], a, b);
return 0;
}
輸出:
2
20
(INT A,B) - >(INT A,INT B)。 http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=141 – DumbCoder 2010-09-17 12:49:26