2017-09-02 50 views
0

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

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

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

+0

我已经试过了藏汉。对不起,不说。在我的问题中加入 – apalomer

+0

它对我来说是按原样运行的。什么编译器和命令行? –

+0

g ++ -o示例example.cpp – apalomer

回答

5

func模板构件函数必须被标记为模板函数调用时:

f.template func<T>(); 

是必需的template关键字以指示左的尖括号<NOT一个小于运算符。见this explanation of this use of the template keyword

add成员函数从参数拿起它的模板类型:

f.add(0.0); // typename N = double 
+0

我可能没有很好地解释自己。我知道为什么'f.add(0.0)'有效。我的问题是如何获得'f。func()'在模板化函数'str()'中工作。 'f.template func ()'完美地工作。为什么?主要是两种模板方法在正常调用时都能正常工作。 – apalomer