Call function with same name as method

I'm trying to define a template class that has some operations on a type. The method ToString should be implemented to call the ToString in the namespace of whatever type the Tools template class has been instantiated with.

namespace X
{
    class SomeType
    {
    };

    std::wstring ToString(SomeType)
    {
       // ...
    }
}

template<class T>
class Tools
{
    static auto ToString(T& t)
    {
        return ToString(t);
    }
}

I get an error in the Tools implementation of ToString. The compiler tries to recursively call the method ToString again instead of calling the ToString in namespace X.

I can't use X::ToString as that will fail when I try to instantiate the Tools class with a type from namespace Y. Eg, if I use:

namespace Y
{
    class SomeOtherType
    {
    };

    std::wstring ToString(SomeOtherType)
    {
       // ...
    }
}

Y::SomeOtherType someOtherType;
auto s = Tools<Y::SomeOtherType>::ToString(someOtherType); // Would fail as SomeOtherType isn't in namespace X.

Is it possible to make this work?

I'm using VS 2015 Update 3. A solutions that work for that is preferred.

Related: calling a global function with a class method with the same declaration


Ok, I might have a solution. Add an intermediate function that is outside the class with a different name, that then calls with the correct name.

Add

namespace ImplementationDetail
{
    template< class T >
    auto ToStringHelper(T& t)
    {
        return ToString(t);
    }
}

template<class T>
class Tools
{
    auto ToString(T& t)
    {
        return ImplementationDetail::ToStringHelper(t);
    }
}

Explicitly use

 return ::X::ToString(t);

to reference the function in the X namespace, irrespective of which namespace the reference comes from.

链接地址: http://www.djcxy.com/p/66538.html

上一篇: 找不到匹配的重载函数C ++ TEMPLATE

下一篇: 调用与方法名称相同的函数