我正在尝试开发一个必须进行模板化并需要一些模板化方法的类。我一直在寻找,很可能是因为我不知道如何解释我的问题,但我一直无法找到解决方案。这里是我的〔实施例:无法使用无参数的模板化方法实例化模板化的类
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)
,但是错误与第一个相似。
我的问题是:我该怎么做才能让编译器完成它的工作?
我已经试过了藏汉。对不起,不说。在我的问题中加入 – apalomer
它对我来说是按原样运行的。什么编译器和命令行? –
g ++ -o示例example.cpp – apalomer