假设我有一个结构
template <typename Args>
struct MyStruct
{
};
但我只希望能够使用std::tuple
实例化来实例化这个类,例如
Mystruct<std::tuple<>> a; // OK
Mystruct<std::tuple<int, int, double>> a; // OK
Mystruct<double> a; // FAIL
我该怎么做?
答案 0 :(得分:4)
这很简单。声明但不定义通用模板:
template<typename T> struct Mystruct;
然后定义专业化:
template<typename... Ts>
struct Mystruct<std::tuple<Ts...>>
{
// stuff
};
答案 1 :(得分:1)
除了krzaq的回答,要获得更好的错误消息,您可能需要使用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
};