[C++]Template Parameters Checking
keywords: C++ Template Parameters Checking
Check for a function’s existence of template parameter
C++20 - requires expressions:
template<class T>
std::string optionalToString(T* obj)
{
constexpr bool has_toString = requires(const T& t) {
t.toString();
};
if constexpr (has_toString)
return obj->toString();
else
return "toString not defined";
}
Pre-C++20 - Detection toolkit:
template<typename T>
using toString_t = decltype( std::declval<T&>().toString() );
template<typename T>
constexpr bool has_toString = std::is_detected_v<toString_t, T>;
C++17 - if constexpr
:
template<class T>
std::string optionalToString(T* obj)
{
if constexpr (has_toString<T>)
return obj->toString();
else
return "toString not defined";
}
Check for the type of a template parameter
Use is_same:
#include <type_traits>
template <typename T>
void foo()
{
if (std::is_same<T, animal>::value) { /* ... */ } // optimizable...
}
Usually, that’s a totally unworkable design, though, and you really want to specialize:
template <typename T> void foo() { /* generic implementation */ }
template <> void foo<animal>() { /* specific for T = animal */ }
Reference:
https://stackoverflow.com/questions/13636540/how-to-check-for-the-type-of-a-template-parameter
Determine if Type is a pointer in a template function
Indeed, templates can do that, with partial template specialization:
template<typename T>
struct is_pointer { static const bool value = false; };
template<typename T>
struct is_pointer<T*> { static const bool value = true; };
template<typename T>
void func(const std::vector<T>& v) {
std::cout << "is it a pointer? " << is_pointer<T>::value << std::endl;
}
https://stackoverflow.com/questions/301330/determine-if-type-is-a-pointer-in-a-template-function
Restrict C++ Template Parameter to Subclass
With a C++11 compliant compiler, you can do something like this:
template<class Derived> class MyClass {
MyClass() {
// Compile-time sanity check
static_assert(std::is_base_of<BaseClass, Derived>::value, "Derived not derived from BaseClass");
// Do other construction related stuff...
...
}
}
Reference:
https://stackoverflow.com/questions/3175219/restrict-c-template-parameter-to-subclass
It is hard enough to remember my opinions, without also remembering my reasons for them! ― Friedrich Nietzsche