I'd like to use a template operator()
but am not sure if it's possible. Here is a simple test case that won't compile. Is there something wrong with my syntax, or is this simply not possible?
struct A {
template<typename T> void f() { }
template<typename T> void operator()() { }
};
int main() {
A a;
a.f<int>(); // This compiles.
a.operator()<int>(); // This compiles.
a<int>(); // This won't compile.
return 0;
}
Template classes and functions can make use of another kind of template parameter known as a non-type parameter. A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument.
Template parameters may have default arguments. The set of default template arguments accumulates over all declarations of a given template.
A template argument for a template template parameter is the name of a class template. When the compiler tries to find a template to match the template template argument, it only considers primary class templates. (A primary template is the template that is being specialized.)
In C++ this can be achieved using template parameters. A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.
Like chris mentioned in the comments, no, not with the shorthand syntax. You must use the full .operator()<T>()
syntax;
If you really want to use templated operator()
and want to avoid writing constructions like a.operator()<int>();
you can add an auxiliary parameter to it:
template <typename T>
struct type{};
struct A
{
template<typename T>
void operator()(type<T>) { }
};
int main()
{
A a;
a(type<int>());
}
Live demo.
In C++14 you can even omit empty brackets in a(type<int>());
via a variable template:
template <typename T>
struct type_{};
template <typename T>
constexpr type_<T> type{};
struct A
{
template<typename T>
void operator()(type_<T>) { }
};
int main()
{
A a;
a(type<int>);
}
Live demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With