模板依赖参数类型

时间:2013-09-16 18:55:02

标签: c++ templates

我不知道为什么这不起作用:

template <typename T>
struct TypeWrapper
{
    typedef T type;
};
template <>
struct TypeWrapper<char*>
{
    typedef std::string type;
};
template <>
struct TypeWrapper<const char*>
{
    typedef std::string type;
};
template <int N>
struct TypeWrapper<char[N]>
{
    typedef std::string type;
};
template <int N>
struct TypeWrapper<const char[N]>
{
    typedef std::string type;
};

class A
{
public:
    template< typename T > 
    A( const typename TypeWrapper<T>::type& t )
    {
        // do smthing
        std::cout << t << std::endl;
    }
};

int main( void )
{
    A a( 42 );

    return 0;
}

我使用Visual Studio 2010编译,我收到以下错误:

error C2664: 'A::A(const A &)' : cannot convert parameter 1 from 'int' to 'const A &'

如果我将A的构造函数更改为此函数,则可以正常工作:

A( const T& t )

但是我想将char *类型作为std :: strings和其他类型的调整来处理,并且复制构造函数(定义一个特定于每种类型的构造函数,这是有效的)

1 个答案:

答案 0 :(得分:2)

我认为以下语法不正确

A( typename const TypeWrapper<T>::type& t )

应该是

A( const typename TypeWrapper<T>::type& t )

A( typename TypeWrapper<T>::type const& t )

无论如何,即使您解决了这个问题,您的示例也无法编译。 VC ++试图调用(编译器生成的)复制构造函数而不是您定义的构造函数,因为模板参数推导将始终在构造函数上失败。原因是标准定义引用嵌套类型名称,如构造函数参数(typename TypeWrapper<T>::type)中的那个是非推导的上下文。

这使您无法构造A,因为必须推导构造函数的模板参数;你无法明确指定它们。


你应该诉诸于超载。

class A
{
public:
    template< typename T > 
    A( T const& t )
    {
        // do smthing
        std::cout << t << std::endl;
    }

    A( std::string const& s )
    {
       std::cout << "string" << std::endl;
    }

    A ( char const *s )
    {
       std::cout << "char *" << std::endl;
    }

    template<std::size_t N>
    A ( const char (&arr)[N] )
    {
       std::cout << "char array" << std::endl;
    }
};
相关问题