gpt4 book ai didi

c++ - 模板相关参数类型

转载 作者:行者123 更新时间:2023-11-30 04:14:33 25 4
gpt4 key购买 nike

我不明白为什么这不起作用:

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 和可能的其他类型调整,而无需复制构造函数(定义特定于每种类型的构造函数,这可行)

最佳答案

我认为以下语法不正确

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;
}
};

关于c++ - 模板相关参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18835225/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com