2015-04-25 115 views
-1

我創造了這個struct了一些簡單的模板數學定義:C++:默認模板參數只有當使用推斷 「<>」

template<class T = float> struct Math{ 
    static constexpr T PI = T(3.14159265359); 
    static constexpr T E = T(2.718281828459); 
    static constexpr T INF = std::numeric_limits<T>::infinity(); 
}; 

我想用這樣的:

float pi = Math::PI; 

即使默認參數Tfloat我也會得到錯誤:

'template<class T> struct Math' used without template parameters 

如果我使用Math<>::PI它可以工作。這是一個編譯器錯誤還是<>括號是強制性的?

+0

爲什麼你不使用'雙'所有他們? –

回答

1

是的,<>括號是強制性的(見here)。

但這裏有一些其他的選項:

使用typedef

typedef Math<> MyDefaultMath 
// or 
typedef Math<float> MyFloatMath 

或剛落模板

struct Math 
{ 
    static constexpr float PI = 3.14159265359f; 
    // ... 
1

Is this a compiler bug or are the <> brackets mandatory?

不,這不是他們是強制性的bug。

但是,您可能想多給一點思考。如果有人使用Math<int>怎麼辦?例如std::numeric_limits::infinity文檔指出以下:

Only meaningful if std::numeric_limits::has_infinity == true

+0

謝謝,這是正確的。我會主要使用'float'和'double'模板。 – tly

1

空括號是強制性的,由標準所要求。從[temp.arg],重點是我的:

When template argument packs or default template-arguments are used, a template-argument list can be empty. In that case the empty <> brackets shall still be used as the template-argument-list. [ Example:

template<class T = char> class String; 
String<>* p; // OK: String<char> 
String* q; // syntax error 

template<class ... Elements> class Tuple; 
Tuple<>* t; // OK: Elements is empty 
Tuple* u; // syntax error 

—end example ]