【发布时间】:2021-09-21 07:25:59
【问题描述】:
这是我的简单程序。我尝试强制使用static_cast,以便编译器知道U 只不过是int。但是,模板仍然无法实例化我的函数 Add 的 int 版本。
将来,我想扩展这个模板,使U 和V 是不同的类型,我的程序仍然可以工作。
但是,目前,即使是相同的类型也无法正常工作。我在这里错过了什么?
编译错误的原因是什么?
#include <iostream>
using namespace std;
template <typename U>
class Addable
{
U x;
public:
Addable(U val) : x{ val } { cout << "Constructor called" << endl; }
template <typename T>
U add(T y);
};
U Addable::add(T y)
{
x += y;
return x;
}
int main()
{
Addable<int> A{ 10 };
int x = A.add(static_cast<int>(10));
cout << x;
return 0;
}
【问题讨论】:
-
附带说明:您的
static_cast与您所拥有的问题无关。另外,看看Why is “using namespace std;” considered bad practice?
标签: c++ c++11 templates member-functions class-template