Is it somehow possible? I want that to enable compile-time passing of arguments. Suppose it's only for user convenience, as one could always type out the real type with template<class T, T X>
, but for some types, i.e. pointer-to-member-functions, it's pretty tedious, even with decltype
as a shortcut. Consider the following code:
struct Foo{
template<class T, T X>
void bar(){
// do something with X, compile-time passed
}
};
struct Baz{
void bang(){
}
};
int main(){
Foo f;
f.bar<int,5>();
f.bar<decltype(&Baz::bang),&Baz::bang>();
}
Would it be somehow possible to convert it to the following?
struct Foo{
template<auto X>
void bar(){
// do something with X, compile-time passed
}
};
struct Baz{
void bang(){
}
};
int main(){
Foo f;
f.bar<5>();
f.bar<&Baz::bang>();
}
Class Template Declarationtemplate <class T> class className { private: T var; ... .. ... public: T functionName(T arg); ... .. ... }; In the above declaration, T is the template argument which is a placeholder for the data type used, and class is a keyword.
Templates in c++ is defined as a blueprint or formula for creating a generic class or a function. To simply put, you can create a single function or single class to work with different data types using templates. C++ template is also known as generic functions or classes which is a very powerful feature in C++.
" typename " is a keyword in the C++ programming language used when writing templates. It is used for specifying that a dependent name in a template definition or declaration is a type.
A template allows us to create a family of classes or family of functions to handle different data types. Template classes and functions eliminate the code duplication of different data types and thus makes the development easier and faster. Multiple parameters can be used in both class and function template.
After your update: no. There is no such functionality in C++. The closest is macros:
#define AUTO_ARG(x) decltype(x), x
f.bar<AUTO_ARG(5)>();
f.bar<AUTO_ARG(&Baz::bang)>();
Sounds like you want a generator:
template <typename T>
struct foo
{
foo(const T&) {} // do whatever
};
template <typename T>
foo<T> make_foo(const T& x)
{
return foo<T>(x);
}
Now instead of spelling out:
foo<int>(5);
You can do:
make_foo(5);
To deduce the argument.
It was added in C++17 Now you can write
template<auto n> struct B { /* ... */ };
B<5> b1; // OK: non-type template parameter type is int
B<'a'> b2; // OK: non-type template parameter type is char
See http://en.cppreference.com/w/cpp/language/template_parameters, point 4 of Non-type template parameter section
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