Boiethios Boiethios - 1 month ago 6
C++ Question

std::is_constructible in a list

I want to find the type from a list I can construct with a template parameter. In this example:

using my_type = typename get_constructible<char *, int, std::string>::type;


my_type
must be
std::string
because in the list
std::string
is the first that can be constructed with a
char *
.

I tried this:

#include <string>

template<typename T, typename... Rest>
struct get_constructible
{
using type = void;
};

template<typename T, typename First, typename... Rest>
struct get_constructible<T, First, Rest...>
{
using type = typename std::conditional<
std::is_constructible<First, T>::value,
First,
get_constructible<T, Rest...>::type
>::type;
};

int main(void)
{
using my_type = get_constructible<char *, int, std::string>::type;
my_type s("Hi!");
}


I do not understand where my logic fails.

Answer

Your logic looks fine, but you're missing a typename on the dependent name get_constructible<T, Rest...>::type:

using type = typename std::conditional<
  std::is_constructible<First, T>::value,
  First,
  typename get_constructible<T, Rest...>::type
//^^^^^^^^
>::type;
Comments