Using template parameters as template parameters

一世执手 提交于 2019-12-31 03:38:06

问题


Why is the following code invalid?

template <typename S, typename T>
struct B{
    void f(T t, S s) {t.f<S>(s); }
};

gcc 4.3.4 complains that it "expected primary-expression before '>' token", i.e. that "S" wasn't a valid primary-expression.


回答1:


You need to specify that f is a template:

void f(T t, S s) {
    t.template f<S>(s);
}

C++ doesn’t know this (at this point) since f’s type depends on the type of the template parameter T. Furthermore, the following syntax would be ambiguous: does < mean the start of a template list or a less-than operator? To help C++ figure that out you need to specify that f is a template, otherwise C++ cannot parse the following part because the parse itself depends on the type of T.




回答2:


You also can rely on type inference to infer the template type instead of explicitly stating it. Then you would have "t.f(s);", which is actually a slightly more generic way to state it: you probably don't care that f is a templated function, you just want it to have some definition for f that accepts an S.



来源:https://stackoverflow.com/questions/3015964/using-template-parameters-as-template-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!