2010-09-17 79 views
15

這可能嗎?運營商作爲模板參數

template<operator Op> int Calc(int a, b) 
{ return a Op b; } 

int main() 
{ cout << Calc<+>(5,3); } 

如果沒有,是不是沒有ifs和開關來實現這一目標的方法?

+0

(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

回答

16

你可以使用函子本:

template<typename Op> int Calc(int a, int b) 
{ 
    Op o; 
    return o(a, b); 
} 

Calc<std::plus<int>>(5, 3); 
+0

它應該是要走的路。非常感謝。 – Xirdus 2010-09-17 12:56:10

+3

@xir:請注意,將它作爲函數參數而不是像Dario顯示的模板參數傳遞給用戶會使用戶更自由,例如,通過有狀態的函子,'bind()'表達式,... – 2010-09-17 13:02:56

+0

可能只是'返回Op()(a,b);',但是像Georg說的那樣,如果你接受它作爲參數,它會更加靈活。 – GManNickG 2010-09-17 14:43:49

16

否 - 模板約類型原始值

可以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()); 
} 
2

爲此,您可以使用多態:

#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; 
} 
+0

正確。但爲了證明這一點非常有用,您必須實際使用運行時多態並使用「操作符」和「接口」。爲這件事情實施'Calc'。然後提前+1! – Dario 2010-09-17 13:41:33

0

如果你指的全球運營商,你已經收到了一些答案。但在某些特定情況下,使用重載的操作符函數也可能會有所幫助。

這可能是微不足道的;儘管如此,它可能是在某些情況下有用這就是爲什麼我發佈了一個例子:

#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