template <typename Type = short>
struct Test {
Test() = default;
Test(Type v) {}
};
int main(int argc, char *argv[]) {
Test<int> t; //int
Test t2(2.2); //double
Test t3; //short
}
模板类型的确定方式:
1. t—在实例化时用<>指定(最常见的方式),优先级最高。
2. t2—用构造函数的方式推导,则必须有带参数的构造函数,也必须保证所有类型都能从构造函数的形参类型里推导出来,优先级次之。
3. t3—通过指定模板参数的默认类型来指定,优先级最低。(如果该类型用于构造函数,要知道实例化方式T t = T())
还有一种方式是通过已经确定的类型,来构造新的类型,例如std::set的定义:(std里经常用到这种方式)
template<class Key, class Compare = less<Key>,
class Allocator = allocator<Key>>
class set {...};