与模板功能的小烦恼

时间:2013-03-27 12:44:42

标签: c++ templates

好吧,假设我有这样的功能

template <typename T>
void Func(std::vector<T> x, T alpha = 1)
{
    // ... do stuff
}

我希望将它与复杂类型一起使用,例如

std::vector<std::complex<double>> x;
Func(x, 5.5);

然后编译器抱怨(VS2010)template parameter 'T' is ambiguous,因为它could be 'double' or 'std::complex<double>'。明显的修复,像这样称呼它

Func(x, std::complex<double>(5.5));

但是,我不想要。为什么不能自动将其转换为复杂类型?

4 个答案:

答案 0 :(得分:4)

它不起作用的原因是因为第一个参数导致T被推导为std::complex<double>而第二个参数导致它被推导为double。在推断参数时,它根本不考虑转换。显然,这使得演绎模糊不清。

您可以借助identity帮助程序强制第二个参数类型不可导出:

template <typename T>
struct identity { typedef T type; };

template <typename T>
void Func(std::vector<T> x, typename identity<T>::type alpha = 1)
{
    // ... do stuff
}

答案 1 :(得分:3)

这个怎么样?

template<typename T>
struct identity {
    typedef T type;
};

template <typename T>
void Func(std::vector<T> x, typename identity<T>::type alpha = 1)
{
    // ... do stuff
}

第二个参数不参与模板参数推导,将使用矢量模板参数。

答案 2 :(得分:1)

如果您需要一个类型与包含类型不同的默认参数,只需使用两种不同的类型:

template <class T, class U>
void Func(vector<T> x, U y);

答案 3 :(得分:0)

如果你不喜欢身份助手,只想让它可以兑换,试试这个:

template <typename T, typename U>
void Func(const std::vector<T>& x, U alphaU = 1)
{
    const T alpha(alphaU); // Convert to T
    // ... do stuff
}

<强>更新

重新评论:我在http://liveworkspace.org处尝试了几个编译器,这段代码对我来说很好:

#include <vector>
#include <complex>

template <typename T, typename U>
void Func(const std::vector<T>& x, U alphaU)
{
   const T alpha(alphaU); // Convert to T
   (void) x;
   (void) alpha;
}

template <typename T>
void Func(const std::vector<T>& x)
{
    Func( x, 1 );
}    

int main()
{
   std::vector<std::complex<double>> v(10);
   Func( v, 5.5 );
   Func( v );
}