无法使用带有参数

时间:2017-09-02 23:42:16

标签: c++ class templates

我正在尝试开发一个必须模板化并需要一些模板化方法的类。我一直在寻找,很可能因为我不知道如何解释我的问题,我一直无法找到解决方案。这是我的例子:

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),但错误与第一个相似。

我的问题是:我该怎么做才能让编译器完成它的工作?

1 个答案:

答案 0 :(得分:5)

调用时,func模板成员函数必须标记为模板函数:

f.template func<T>();

需要template关键字来表示左侧括号< 小于运算符。请参阅this explanation of this use of the template keyword

add成员函数从参数中选取其模板类型:

f.add(0.0); // typename N = double
相关问题