在自己的模板类的构造函数中定义并调用模板函数

Define and then call template function inside constructor of its own template class

本文关键字:定义 调用 函数 自己的 构造函数      更新时间:2023-10-16

我正试图在自己的模板类中使用一个模板函数。我们如何声明和调用这个函数?以下是我认为正确的代码,故意没有达到任何说明目的:

template<typename T> class TEMPLATE_CLASS
{
    // The template constructor
    TEMPLATE_CLASS(T value)
    { 
        // Here I call the class's template member function
        // ... but fails
        T variable = setVariable(value);
    }
    template<typename U>
    T setVariable(T value_to_set)
    {
        return value_to_set;
    }
}

在这个特定的例子中,当您将T传递给函数时,编译器无法确定U应该是什么。通常模板类型用于其中一个参数,然后编译器可以从中推断类型。

可以使用setVariable<int>(value)来指示U应该是int,但从这个小例子中很难判断它有什么意义。

在您的代码中,将此方法作为模板方法是没有意义的,因为您在她的范围内的任何地方都不使用U。但如果你不想这样做,你的代码应该是这样的:

template<typename T> class TEMPLATE_CLASS
{
    // The template constructor
    TEMPLATE_CLASS(T value)
    { 
        // Here I call the class's template member function
        // ... but fails
        T variable = setVariable(value);
    }
    template<typename U>
    U setVariable(U value_to_set)
    {
       return value_to_set;
    }
}

根据情况,如果您不想在方法内部对value_to_set执行任何操作,例如转换为T,您可以从中返回T