当编译器可以推断出模板参数? [英] When a compiler can infer a template parameter?

查看:145
本文介绍了当编译器可以推断出模板参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时它不能工作:

 模板< class T& 
void f(T t){}

template< class T>
class MyClass {
public:
MyClass(T t){}
};

void test(){
f< int>(5);
MyClass< int> mc(5);
f(5);
MyClass mc(5); //这不工作
}

是否有办法以上?也就是说强制编译器从构造函数参数中推断模板参数。



这将在以后修复,还是有很好的理由不?



当编译器可以推断模板参数时,一般规则是什么?

解决方案

模板参数因此,当可以从模板参数中推导出参数类型时,推断为函数模板




$ b

 模板< typename T> 
void f(T t);

template< typename T>
void f(std :: vector< T> v);

但不在此处:

  template< typename T> 
T f(){
return T();
}

而不是在类模板 >

所以你的问题的通常的解决方案是创建一个包装函数,类似于标准库函数 std :: make_pair

 模板< class T> 
class MyClass {
public:
MyClass(T t){}
};

template< typename T>
MyClass< T> MakeMyClass(T t){return MyClass(t); }

然后调用 MakeMyClass 类。


Sometimes it works sometimes not:

template <class T> 
void f(T t) {}

template <class T>
class MyClass {
public:
  MyClass(T t) {}
};

void test () {
  f<int>(5);
  MyClass<int> mc(5);
  f(5);
  MyClass mc(5); // this doesn't work
}

Is there a way to hack around the example above? I.e. force the compiler to infer the template parameter from constructor parameter.

Will this be fixed in the future, or is there a good reason not to?

What is the general rule when compiler can infer template parameter?

解决方案

Template parameters can be inferred for function templates when the parameter type can be deduced from the template parameters

So it can be inferred here:

template <typename T>
void f(T t);

template <typename T>
void f(std::vector<T> v);

but not here:

template <typename T>
T f() {
  return T();
}

And not in class templates.

So the usual solution to your problem is to create a wrapper function, similar to the standard library function std::make_pair:

template <class T>
class MyClass {
public:
  MyClass(T t) {}
};

template <typename T>
MyClass<T> MakeMyClass(T t) { return MyClass(t); }

and then call MakeMyClass to instantiate the class.

这篇关于当编译器可以推断出模板参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆