c++ - 多参数模板函数、重载和歧义错误

标签 c++ templates

假设我正在编写某种转换运算符,我想这样使用它:

SomeType a;
AnotherType b = conv<AnotherType>(a);

首先,我编写基本(默认)函数:

template <typename T, typename U>
inline T conv(const U& a)
{
    return T(a);
}

完全特化(或非模板重载)不是问题,但是,当我想做这样的事情时:

template <typename T>
inline Point<T> conv(const Ipoint& p)
{
    return Point<T>(p.x, p.y);
}

由于歧义,我无法再编写从 Ipoint(例如到 FunkyPoint< T >)的任何转换函数,最后我的用法很尴尬:

Ipoint a;
Point<double> b = conv<double>(a); //ugly!
//Point<double> b = conv<Point<double> >(a); //I want that, but it (obviously) does not compile.

有什么办法可以很好地做到这一点吗?

最佳答案

在类模板中实现主体,然后您可以部分特化:

template < typename T, typename U >
struct convert
{
  static T apply(U const& u) { return T(u); }
};<p></p>

<p>template < typename T, typename U >
T conv(U const& u) { return convert<T,U>::apply(u); }</p>

template < typename T > struct convert<Point<T>, Ipoint> { static Point apply(Ipoint const& u) { return Point(u.x, u.y); } };

应该可以,但未经测试。

关于c++ - 多参数模板函数、重载和歧义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2885132/

相关文章:

c++ - 将额外的字节填充到要通过网络发送的 flatbuffer 的缓冲区指针

c++ - 是否使用对通过 reinterpret_cast 未定义行为进行转换的指针的引用?

c++ - Rand() % 14 仅生成值 6 或 13

c++ - CRTP 类示例

c++ - SDL2 不接收窗口事件

c++ - 在 Xcode 中安装 SFML 时出现问题 - 找不到合适的图像

c++ - Visual Studio 中 <variadic template> 模板参数具有默认值编译错误

c++ - 我的模板类的多个定义

c++ - Qt C++ 在函数模板中使用约束

c++ - 如果实例化,如何使模板化变量专门化在编译时失败?