2017-06-04 55 views
0

如何從構造函數推斷模板參數?如何從構造函數推斷模板參數?

template<class $sign, signed $size> 
class Integer; 

template<> 
class Integer<signed, 8> 
{ 
public: 
    typedef signed long long type; 
}; 

typedef Integer<signed, 8>::type Int64; 

template<class $sign, signed $size> 
class Integer 
{ 
public: 
    Integer(Integer<$sign, $size>::type a){} 
    // 1LL(Int64) => Integer<$sign, $size>::type => $sign, $size 
    //How to infer <$ sign, $ size> 
}; 

int main() { 
    Integer a(1LL); 
    return 0; 
} 

如何從構造函數推斷模板參數?

1LL(Int64的)=>Integer<$sign, $size>::type => $符號,$大小

如何推斷<$ sign, $ size>

回答

0

http://en.cppreference.com/w/cpp/language/class_template_deduction,你可以看到這個功能只適用起始C++ 17。儘管您可能需要通過特質類或明確的演繹指南添加另一層間接性,以使您的示例正常工作。

如果您有支持-std=c++1z-std=gnu++1z的編譯器,那麼您也可以使用它。

這裏是一個工作示例https://wandbox.org/permlink/HqmitAQxSziZx8IC(相同的代碼粘貼下面也)

#include <iostream> 

using std::cout; 
using std::endl; 

template <typename IntegerType, int width> 
class Integer { 
public: 
    Integer(IntegerType) { 
     cout << __PRETTY_FUNCTION__ << endl; 
    } 
}; 

template <> 
class Integer<signed, 8> { 
public: 
    Integer(signed) { 
     cout << __PRETTY_FUNCTION__ << endl; 
    } 
}; 

template <typename IntegerType> 
Integer(IntegerType) -> Integer<IntegerType, sizeof(IntegerType)>; 

int main() { 
    Integer{1LL}; 
    return 0; 
} 
+0

舉一個例子 謝謝 –

+0

@呂詩銘更新我的回答 – Curious

+1

非常感謝你 –

相關問題