c++ - How do I call a templated member function without knowing whether or not the class is a template? -
suppose have following macro:
#define call_foo(x) x.foo<int>();
this macro call templated foo
function template argument int
, , compile long x
not template type. if is, need define second variant of macro handle template types:
#define call_foo_templated(x) x.template foo<int>();
how can create macro call template member function foo
regardless of whether or not x
dependent name?
the answer you're looking for, in [temp.names], template
required when:
when name of member template specialization appears after
.
or->
in postfix-expression or after nested-name-specifier in qualified-id, , object expression of postfix-expression type-dependent or nested-name-specifier in qualified-id refers dependent type, name not member of current instantiation (14.6.2.1), member template name must prefixed keywordtemplate
.
but while there restrictions on name referred to:
a name prefixed keyword
template
shall template-id or name shall refer class template.
there not restrictions on "dependence-ness" of it:
[ note: case
typename
prefix,template
prefix allowed in cases not strictly necessary; i.e., when nested-name-specifier or expression on left of->
or.
not dependent on template-parameter, or use not appear in scope of template. —end note]
so following compile fine:
struct x { template <typename > void foo() { } }; int main() { x{}.template foo<int >(); // template keyword not strictly necessary }
the real answer though is: don't use macro such thing. write out function call. thank later. added bonus @ call site, know whether or not template
keyword required, can use precisely necessary.
Comments
Post a Comment