c++ - 使用 ptr-ref 类型的模板特化和特化规则

标签 c++ templates template-specialization

使用 MSVC 2010,我得到以下行为:

template <class T> class Boogy
{
public:
    void Fn( T in )
    {
    }

    void Fn2( const T& in)
    {
    }
};

template <> void Boogy<int>::Fn( int in ) //builds ok
{
}

template <> void Boogy<int*>::Fn( int* in ) //builds ok
{
}

template <> void Boogy<int>::Fn2( const int& in ) //builds ok
{
}

template <> void Boogy<int*>::Fn2( const int*& in ) //DOES NOT BUILD
{
}

typedef int* intStar;
template <> void Boogy<intStar>::Fn2( const intStar& in ) //builds ok
{
}

显然,我已经想出了一个“黑客”来解决我的问题,但为什么需要这个黑客?我们到底应该这样做吗?我所在的代码库有数十个实例,其中模板类对某些成员函数有一些专门化 - 而不是整个类。一位同事坚决认为这是不允许的。

TIA。

最佳答案

它应该是int * const &。您有 T = int *,因此 const T = T const = int * const

请记住,U const & 表示“对常量 U 的引用”,而不是“U 的常量引用”——后者没有意义,因为 C++ 中的引用变量总是常量,即不能重新定位。在您的情况下,U 是一个指向 int 的指针,而不是一个指向 const-int 的指针,这是两种不同的类型。

您当然也可以为 int const * 添加单独的特化:

template <> void Boogy<int const *>::Fn2(int const * const & in) { /* ... */ }

关于c++ - 使用 ptr-ref 类型的模板特化和特化规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10795187/

相关文章:

c++ - 递归模板解释C++

javascript - 将回调作为参数发送给 QJSValue::callAsConstructor()

c++ - 创建着色器文件

c++ - 仅当底层类型具有这些构造函数时才实现模板类型构造函数

python - Jinja2 未获取模板 "No template file present: default.j2 "

c++ - 模板化类的成员函数的特化不起作用

c++ - 仿函数 operator() 的条件特化

c++ - 为什么在这种情况下模板实例化深度会超过限制?

javascript - WebAssembly.instantiate 既没有调用,也没有在 v8 嵌入中捕获

可以使用虚拟分派(dispatch)或类似没有对象上下文的静态函数来调用 C++ 类方法