如何从构造函数推断模板参数???
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)=&gt; Integer<$sign, $size>::type
=&gt; $ sign,$ size
如何推断<$ sign, $ size>
答案 0 :(得分:0)
http://en.cppreference.com/w/cpp/language/class_template_deduction正如您所看到的,此功能仅在启动C ++ 17时可用。虽然您可能需要通过traits类或显式演绎指南添加另一个间接层,以使您的示例正常工作。
如果您的编译器支持-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;
}