![]() |
#2
rjsp2023-01-17 14:52
|

#include <bits/stdc++.h>
// #include <boost/lexical_cast.hpp>
using namespace std;
class Caster1 {
public:
template<typename R, typename T>
R cast(const T& t) {
stringstream ss;
ss << t;
R r;
ss >> r;
return r;
}
};
// class Caster2 {
// public:
// template<typename R, typename T>
// R cast(const T& t) {
// return boost::lexical_cast<R>(t);
// }
// };
template<typename CAST_T>
class Test {
public:
template<typename R, typename T>
R cast(const T& t) {
return CAST_T().cast<R>(t); // 此处会报错
}
};
int main() {
cout << Caster1().cast<double>("3.14") << endl;
// cout << Caster2().cast<double>("3.14") << endl;
Test<Caster1> test;
cout << test.cast<double>("3.14") << endl;
return 0;
}
报错为
test_template.cpp: In member function ‘R Test<CAST_T>::cast(const T&)’:
test_template.cpp:31:31: error: expected primary-expression before ‘>’ token
31 | return CAST_T().cast<R>(t);
这是为什么呢,似乎不能使用模板类创建的对象的模板成员函数。
|