如何将转换运算符外部化?

SSi*_*ht3 4 c++ class

我如何制作它以便以下代码在课外进行外部化:

template<typename TemplateItem>
class TestA
{
     operator const int (){return 10;}
};
Run Code Online (Sandbox Code Playgroud)

所以看起来像:

template<typename TemplateItem>
class TestA
{
    operator const int ();
};

template<>
TestA<int>::operator const int()
{
    //etc etc
}
Run Code Online (Sandbox Code Playgroud)

所以我可以专门针对不同模板类型的函数?

Ker*_* SB 5

写这个:

template <typename T> class TestA
{
  operator const int();
};

template <typename T> TestA<T>::operator const int()
{
  return 10;
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,"内联"的标准反义词通常是"脱节"的.此外,我可能会创建该函数const,就像通常使用转换运算符一样(允许来自常量对象的转换).

您可以专门化整个类,也可以只使用成员函数.仅对于成员函数,请写下:

template <> TestA<int>::operator const int() { /* ... */ }
Run Code Online (Sandbox Code Playgroud)

对于整个类的特化,语法是这样的:

template <> class TestA<int>
{
  operator const int();
};
TestA<int>::operator const int() { /*...*/ }
Run Code Online (Sandbox Code Playgroud)

  • @MooingDuck和Kerrek - 我想*我明白你在说什么,但为什么[这个](http://ideone.com/DaTAC)编译并运行? (3认同)