如何在非模板化类中专门化没有参数的模板化方法

How do you specialize a templated method with no parameters in a non-templated class?

本文关键字:方法 专门化 参数      更新时间:2023-10-16

我正在尝试在非模板化类中专门化模板化方法,其中该方法的返回类型包括模板化类型 - 此方法不带参数。我一直在四处寻找,试图通过反复试验来编译东西,但无济于事。

如何生成此代码?这样的语法甚至可能吗?(我尝试专门化的模板化方法是cBar::getFoos,如下面的评论所示。

下面精简了示例代码:

#include <vector>
////////////////////////////////////////////////////////////////////////////////
// the non-templated class below contains std::vector objects of these types
// (tBuiltInType is an int, float, or bool - but hopefully that's not an
// assumption that needs to be made, as I'd like to include more complex types)
template< typename tBuiltInType >
class cFoo
{
public:
    // ...
    void doSomething()
    {
        // ... (unimportant what happens here, but stuff happens)
    }
private:
    std::vector< tBuiltInType > m_objects;
};
////////////////////////////////////////////////////////////////////////////////
// this contains the templated method I'm trying to specialize - getFoos
class cBar
{
public:
    // ...
    // this is the method I'm trying to specialize by contained type (see private area)
    // getFoos< int >() would return m_intFoos, etc.
    template< typename tBuiltInType >
    std::vector< cFoo< tBuiltInType > > &getFoos();
    // (probably unimportant) example use    
    template< typename tBuiltInType >
    void doSomething()
    {
        for ( cFoo< tBuiltInType > &foo : getFoos< tBuiltInType >() )
            foo.doSomething();
    }
private:
    std::vector< cFoo< int > >   m_intFoos;
    std::vector< cFoo< bool > >  m_boolFoos;
    std::vector< cFoo< float > > m_floatFoos;
};
////////////////////////////////////////////////////////////////////////////////
// some (also probably unimportant) example usage code
int main()
{
    cBar bar;
    bar.doSomething< int >();
    bar.doSomething< bool >();
    bar.doSomething< float >();
    return 0;
}

(我正在探望我的家人并且没有笔记本电脑,所以我通常的开发设置不可用 - 我可以在我一直尝试的在线编译器中发布尝试的错误,但我怀疑它在这里会有多大好处,因为没有多少人会看到一个晦涩的在线编译器错误并知道该怎么做,所以我会跳过那一点来压缩问题文本。

继续专门

化它,在课堂之外:

template<>
std::vector< cFoo< int > >& cBar::getFoos() { return m_intFoos; }

工作示例

所以你想让getFoos<int>()返回m_intFoos等?我认为最简单的方法是引入一个空的标签调度类型:

template <typename T> struct empty { };
template< typename tBuiltInType >
std::vector< cFoo< tBuiltInType > >& getFoos() 
{
    return getFoosImpl(empty<tBuiltInType>{} );
}

然后提供正确的重载:

std::vector< cFoo<int> >& getFoosImpl(empty<int> ) { return m_intFoos; }
std::vector< cFoo<bool> >& getFoosImpl(empty<bool> ) { return m_boolFoos; }
std::vector< cFoo<float> >& getFoosImpl(empty<float> ) { return m_floatFoos; }