Edit: This funcion have to check types one by one and return obj of any that will satisfy condition or nullptr.
template <typename... Args, typename = std::enable_if_t<(sizeof...(Args) == 0)>()>
std::nullptr_t f() { return nullptr; }
template <typename T, typename... Args>
BaseClassOfAllArgs* f() {
if (<some condition related to T...>)
return new T;
return f<Args...>();
}
This code works for me. But I wonder if is it possible to rewrite this code to use concept? I mean something like this:
template <typename... Args>
concept NoArgs = (sizeof...(Args) == 0);
and then use it instead of std::enable_if(this code doesnt work)
template <NoArgs Args>
std::nullptr_t f() { return nullptr; }
template <typename T, typename... Args>
BaseClassOfAllArgs* f() {
if (<some condition related to T...>)
return new T;
return f<Args...>();
}
EDIT: Here is working example of code after taking some tips from guys in comments. After I added 'Base' to the template it turns out that EmptyPack concept is no longer needed. And First template naturally needs 3 typenames. However, I am not sure about this concept EmptyPack. Is it really making my program ill-formed no diagnostic required?
#include <iostream>
#include <type_traits>
#include <typeinfo>
class X {};
class A : public X {};
class B : public X {};
class C : public X {};
class D : public C {};
class E {};
template<class T, class... Args >
concept DerivedsOfBase = (std::is_base_of_v<T, Args> && ...);
template<typename... Args>
concept EmptyPack = sizeof...(Args) == 0;
template<typename T>
std::nullptr_t f() {
std::cout << "End of the types list" << std::endl;
return nullptr;
}
template<typename Base, typename T, typename... Args> requires DerivedsOfBase<Base, T, Args...>
Base* f() {
std::cout << typeid(T).name() << std::endl;
if (<some condition related to T>)
return new T;
return f<Base, Args...>();
}
int main()
{
auto ptr = f<X, A, B, C>();
auto ptr2 = f<X, A, B, D>();
//auto ptr3 = f<X, A, B, E>(); // compile error
return 0;
}