我正在尝试开发一个必须模板化并且需要一些模板化方法的类。我一直在寻找,很可能是因为我不知道如何解释我的问题,所以我一直无法找到解决方案。这是我的例子:
template<typename T>
class TestClass{
public:
template<typename M>
TestClass(M val): val_(T(val)){}
template<typename N>
N func() {
return N(val_);
}
T get() {
return val_;
}
template<typename N>
N add(N val) {
return N(val_) + val;
}
private:
T val_;
};
这个类将在模板函数中被调用,比如这个:
template<typename T>
std::string str(TestClass<T> f)
{
std::ostringstream out;
out << f.func<T>();
out << "\n";
out << "get: ";
out << f.get();
out << "\n";
out << f.add<T>(0.0);
return out.str();
}
这是一个用法示例:
int main(int argc, char** argv){
TestClass<double> t('a');
std::cout<<"Manual output: \n";
std::cout<<"func: "<<t.func<double>()<<std::endl;
std::cout<<"get: "<<t.get()<<std::endl;
std::cout<<"add: "<<t.add<double>(0)<<std::endl;
std::cout<<"operator<< output: \n";
std::cout<<str(t)<<std::endl;
return 0;
}
我编译时没有 std::string str(TestClass<T> f)
main
中的函数及其用法我观察到所需的行为。但是,我无法编译此代码并出现以下错误:
error: expected primary-expression before '>' token
out << f.func<T>();
^
expected primary-expression before ')' token
out << f.func<T>();
^
expected primary-expression before '>' token
out << f.add<T>(0.0);
^
编译器还会产生关于 <<
的错误运算符和 f.func<T>()
的事实和 f.add<T>
类型尚未解决。如果我在 str()
内的调用中删除模板化部分:
template<typename T>
std::string str(TestClass<T> f)
{
std::ostringstream out;
out << f.func();
out << "\n";
out << "get: ";
out << f.get();
out << "\n";
out << f.add(0.0);
return out.str();
}
那么,编译错误是:
no matching function for call to 'TestClass<double>::func()'
out << f.func();
^
candidate is:template<class N> N TestClass<T>::func() [with N = N; T = double]
N func() {
^
couldn't deduce template parameter 'N'
out << f.func();
^
这是有道理的,因为 func()
无法推断类型。我也尝试过,使用 f.func<T>()
和 f.add(0.0)
但错误与第一个错误类似。
我的问题是:我应该怎么做才能让编译器完成它的工作?
最佳答案
func
模板成员函数在调用时必须标记为模板函数:
f.template func<T>();
template
需要关键字来指示左尖括号 <
NOT 是小于运算符。参见 this explanation of this use of the template keyword .
add
成员函数从参数中获取其模板类型:
f.add(0.0); // typename N = double
关于c++ - 无法使用没有参数的模板化方法实例化模板化类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46019119/