Undefined Sample Specification Problem

I am currently porting a bunch of code that was previously compiled using Visual Studio 2008. This code has this scheme:

template <typename T> 
T convert( const char * s )
{
    // slow catch-all
    std::istringstream is( s );
    T ret;
    is >> ret;
    return ret; 
}

template <typename T, typename T2>
T convert( T2 * s )
{
    return convert<T>( static_cast<const char*>( s ));
}

template <typename T, typename T2>
T convert( T2 s )
{
    return T( s );
}

template <>
inline int convert<int>( const char * s )
{
    return (int)atoi( s );
}

As a rule, there are many specializations of a template function with different types of return values, which are called as follows:

int i = convert<int>( szInt );

The problem is that these template specializations lead to "Ambiguous template specialization." If it were something other than the return type that distinguished these specialized functions, I could just use overloads, but that is not an option.

How can I solve this problem without changing all the places that are called by the conversion functions?

, . , , , - , , *. GCC , , .

2 cpp, . " ", . - , .

#include <iostream>
#include <sstream>

template <typename T> 
T convert( const char * s )
{
    // this is a slow slow general purpose catch all, if no specialization is provided
    std::istringstream is( s );
    T ret;
    is >> ret;
    return ret; 
}

// general purpose 1
template <typename T, typename T2>
T convert( T2 * s )
{
    return convert<T>( static_cast<const char*>( s ));
}

// general purpose 2
template <typename T, typename T2>
T convert( T2 s )
{
    return T( s );
}

// Type specialized

template <>
inline float convert<float>( const char * s )
{
    return (float)atof( s );
}

int main( int argc, const char * sz[] )
{
    return 0;
}
+3
1

- return convert<T>( static_cast<const char*>( s )); ( - , ) T convert( const char * s ) T = float. , , , .

inline float convert<float>( const char * s ) ( const char*), g++ 4.2.

+1

Source: https://habr.com/ru/post/1745578/


All Articles