本文介绍了c ++模板铸造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点迷失在如何铸造模板。我有一个函数foo,它接受类型 ParamVector< double> * 的参数。我想传递一个 ParamVector< float> * ,我不知道如何重载我的 ParamVector 类,Google并没有帮助我。有没有人有一个如何做到这一点的例子?谢谢。



编辑:添加一些代码,对不起,我是一个白痴,并没有很好地说明原来的问题;

 模板< class T> class ParamVector 
{
public:
vector< T>侏儒
vector< T> data_params;
}

template< class T> class ParamVectorConsumer
{
public:
ParamVector< T>测试;
}

ParamVector< float>测试仪;
ParamVectorConsumer< double>缺点
cons.ParamVector = tester

将无法编译。我想知道如何写它,以便我可以将float版本的测试仪转换为ParamVector双。感谢



EDIT2:投放是错误的词。我不介意写额外的代码,我只需要知道如何让这个被编译器接受,这样我可以写一些转换代码。

解决方案

我不确定,但也许你需要这样的:

  typename TypeT> 
struct ParamVector
{
template<类型名NewTypeT>
operator ParamVector< NewTypeT>()
{
ParamVector< NewTypeT>结果;
//做一些转换事情
return result;
}

template<类型名NewTypeT>
ParamVector(const ParamVector< NewTypeT>& rhs)
{
// convert
}

template<类型名NewTypeT>
ParamVector&运算符=(const ParamVector< NewTypeT>& rhs)
{
//做一些转换命令
return * this;
}


};
ParamVector< double> d1;
ParamVector< float> f1;
f1 = d1;

您可以选择使用转换操作符或operator = - 我在示例中提供了两者。 p>

I'm a little lost in how to cast templates. I have a function foo which takes a parameter of type ParamVector<double>*. I would like to pass in a ParamVector<float>*, and I can't figure out how to overload the casting operator for my ParamVector class, and Google isn't helping me that much. Does anyone have an example of how to do this? Thanks.

EDIT: Adding some code, sorry I'm an idiot and didn't phrase the original question well at all;

template<class T> class ParamVector 
{
public:
	vector <T> gnome;
	vector <T> data_params;
}

template<class T> class ParamVectorConsumer
{
 public:
 ParamVector<T> test;
}

ParamVector<float> tester;
ParamVectorConsumer<double> cons;
cons.ParamVector = tester

will fail to compile. I would like to know how to write it so that I can cast the float version of tester to a ParamVector double. Thanks

EDIT2: Casting was the wrong word. I don't mind writing extra code, I just need to know how to get this to be accepted by the compiler so that I can write some sort of conversion code.

解决方案

I'm not sure but maybe you need some like this:

template< typename TypeT >
struct ParamVector
{
    template < typename NewTypeT >
    operator ParamVector< NewTypeT >()
    {
    	ParamVector< NewTypeT > result;
    	// do some converion things
    	return result;
    }

    template< typename NewTypeT >
    ParamVector( const ParamVector< NewTypeT > &rhs )
    {
    	// convert
    }

    template < typename NewTypeT >
    ParamVector& operator=( const ParamVector< NewTypeT > &rhs )
    {
    	// do some conversion thigns
    	return *this;
    }


};
ParamVector< double > d1;
ParamVector< float > f1;
f1 = d1;

You can choose use conversion operator or operator= - I've provided both in my example.

这篇关于c ++模板铸造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 02:25