如何用不同的数据类型调用同一个函数?

How to call the same function with different datatype?

这里有一个 class 可以用不同的数据类型调用:

template<class TDataType> 
void SetProperties(IndexType PropertiesId, 
                   const Variable<TDataType>& rVariable, 
                   const TDataType& Value)
{
    mpModeler->SetProperties(PropertiesId, rVariable, Value);
}

其中 Modeler::SetProperties 定义为:

template<class TDataType> 
void SetProperties(IndexType PropertiesId, 
                   const Variable<TDataType>& rVariable, 
                   const TDataType& Value)
{
    if (mpModel->GetProperties(PropertiesId).get() == 0)
    {
        mpModel->AddProperties(PropertiesId, Properties::Pointer(new Properties(*mpModel)));
    }

    PropertyFunction<TDataType>::Pointer constant_property(new ConstantProperty<TDataType>(Value));

    mpModel->GetProperties(PropertiesId)->SetProperty(rVariable, constant_property);
}

class SetProperties 调用者:

yyvsp[0].statement_handler->Execute(mpKernel); 

其中 Execute() 定义为:

template<class TDataType> class GeneratePropertiesStatement : public Statement
{
public:

    GeneratePropertiesStatement(int Id, 
                                const Kratos::Variable<TDataType>& rVariable, 
                                const TDataType& Value) : mId(Id), 
                                                         mVariable(rVariable), 
                                                         mValue(Value){}

    void Execute(Kratos::Kernel* pKernel)
    {
        pKernel->SetProperties(mId, mVariable, mValue);
    }

    int mId;
    Kratos::Variable<TDataType> mVariable;
    TDataType mValue;
};

通过以下语句将单个数据或多个数据传递给Value:

单条数据:

yyval.statement_handler = new GeneratePropertiesStatement<double>(yyvsp[-4].integer_value, *yyvsp[-2].double_variable, yyvsp[0].double_value);

其中 yyvsp[0].double_value 定义为 double;

多个数据:

yyval.statement_handler = new GeneratePropertiesStatement<Kratos::Vector<double> >(yyvsp[-4].integer_value, *yyvsp[-2].vector_double_variable, *yyvsp[0].vector_double_value);

其中 *yyvsp[0].vector_double_value 定义为 vector.

但是上面的实现依赖于一些外部数据,需要直接调用函数SetProperties。我定义了以下参数并成功调用了函数:

int i;
const Kratos::Variable<double>* double_variable;
double regionmapi;
...
pKernel->SetProperties(i, *double_variable, regionmapi);

但是,当我定义如下参数并调用函数传递多个数据时,它失败了:

double tmp3[3];
std::vector<double>aa;
for (int i = 0; i < 3; i++)aa.push_back(tmp3[i]);
pKernel->SetProperties(i, *double_variable, aa);

谁能帮我看一下?

在使用多个数据调用 SetProperties 时,第二个参数必须是 Kratos::Variable<std::vector<double>> 类型,以便与 std::vector<double> 类型的第三个参数保持一致.从您显示的代码来看,第二个参数的类型似乎是 Kratos:Variable<double>,它与第三个参数冲突。