Suppose I have a struct
template <typename Args>
struct MyStruct
{
};
But I only want to be able to instantiate this class with std::tuple
instantiations, eg
Mystruct<std::tuple<>> a; // OK
Mystruct<std::tuple<int, int, double>> a; // OK
Mystruct<double> a; // FAIL
How can I do this?
This is fairly simple. Declare but not define a general template:
template<typename T> struct Mystruct;
then define a specialization:
template<typename... Ts>
struct Mystruct<std::tuple<Ts...>>
{
// stuff
};
In addition to krzaq's answer, to have a better error message, you might want to use static_assert
// The traits:
template <typename T>
struct is_a_tuple : std::false_type {};
template <typename ... Ts>
struct is_a_tuple<std::tuple<Ts...>> : std::true_type {};
// Your structure (for error message)
template <typename T>
struct MyStruct
{
static_assert(is_a_tuple<T>::value, "T should be a std::tuple");
};
// Your structure (for std::tuple)
template <typename ... Ts>
struct MyStruct<std::tuple<Ts...>>
{
// Your implementation
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.