2016-12-31 91 views
1

指向成員指針作爲非類型模板參數的用例是什麼?實際使用指向成員非類型模板參數的指針

例如:

class X { 
public: 
    int n; 
}; 


template <typename T, T nontype_param> 
class C 
{ 
public: 
    void doSomething() 
    { 
     //what goes here to access or use nontype_param? 
    } 
}; 

void test() 
{ 
    C<int X::*, &X::n> c; 
    c.doSomething(); 
} 
+0

也許與POD結構一起使用?沒有一定的背景,確實很難說出任何事情。 –

+2

類似'X x; x。* nontype_param = 42;'? – Jarod42

+0

@Someprogrammerdude - 正是我在閱讀模板時遇到的情況。真的沒有比這更多的上下文,因此關於用例的問題:) – tomatoRadar

回答

0

行情從Bjarne的書:

A型模板參數可以被用來作爲一種後來在模板參數列表。例如:

template<typename T, T default_value> 
class Vec { 
// ... 
}; 

Vec<int,42> c1; 
Vec<string,""> c2; 

當與默認模板參數(第25.2.5節)結合使用時,這變得特別有用;對於 示例:

template<typename T, T default_value = T{}> 
class Vec { 
    // ... 
}; 

Vec<int,42> c1; 
Vec<int> c11; // default_value is int{}, that is, 0 

Vec<string,"for tytwo"> c2; 
Vec<string> c22; // default_value is string{}; that is, "" 
+0

指向成員非類型模板參數__ – Danh