在自己的模板类的构造函数中定义并调用模板函数
Define and then call template function inside constructor of its own template class
我正试图在自己的模板类中使用一个模板函数。我们如何声明和调用这个函数?以下是我认为正确的代码,故意没有达到任何说明目的:
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
。
相关文章:
- 使用用户定义的参数调用future/async并调用类方法
- 从python调用openMP共享库时,未定义opnMP函数
- 尝试调用 .h 文件中定义的变量时出现变量未定义错误
- 为用户定义的类正确调用复制构造函数/赋值运算符
- 如何知道链自定义算子<<调用次数?
- 自定义 std::fstream,std::filebuf 的溢出和下溢函数未为每个字符调用
- C++调用和定义不匹配
- 在 Microsoft Access SQL 中调用自定义 DLL 函数时传递的内存地址无效
- Tbb 库:错误:编写自定义类函数而不是 lambda 表达式时,对函数的调用不匹配
- clang:错误:链接器命令失败,退出代码为 1(使用 -v 查看调用) - 体系结构的未定义符号 x86_64:
- 调用 Win32 API 函数时未定义的引用
- Linux c++.在预加载的共享库中定义的基类的崩溃调用函数
- C++:对函子重载调用运算符的未定义引用
- 在销毁期间从另一个线程调用对象上调用方法是否未定义行为?
- c++ 中的自定义分配器,用于不调用secure_string实现
- 如何生成C++定义调用的动态生成
- 根据给定的类型定义调用 std::to_string 或 std::to_wstring
- 制作对inner_product(C++STL)的自定义调用
- c++自定义调用约定
- 已经或将要使用C++14或C++1z使其不再未定义调用委托类成员函数指针