【问题标题】:How to specialize variadic template class for one type?如何为一种类型专门化可变参数模板类?
【发布时间】:2021-02-21 18:50:47
【问题描述】:

我正在尝试专门针对特定类型的可变参数模板类。

我正在努力实现这一目标:

template<typename... Ts>
class myclass
{
   ///...
};

template<>
class myclass<int... N>
{
   ///...
};

我得到了这个错误:

error C2760: syntax error: unexpected token 'int', expected 'expression'
error C2187: syntax error: '...' was unexpected here
error C2065: 'N': undeclared identifier
error C2913: explicit specialization; 'ex::vec' is not a specialization of a class templa

谁能提示我做错了什么?

【问题讨论】:

  • 你不能用值来专门化为类型定义的类。
  • 你打算如何使用它?请添加示例。
  • 为确保我理解,您希望您的专长处理 myclass&lt;int&gt;myclass&lt;int, int&gt;myclass&lt;int, ..., int&gt;,对吗?
  • @NathanOliver,正确。
  • 请提供该模板的用例示例。您的定义示例没有意义。

标签: c++ templates variadic-templates


【解决方案1】:

您的myclass 被声明为模板参数的可变参数列表

template<typename... Ts>
class myclass

您可以专门针对特定类型,而不是特定值,如您的问题(已纠正语法,但对于类型/值问题仍然错误)

template <int N>
class myclass<N...>

如果您将值作为类的模板参数,则不同,例如

template <typename ... Ts>
class myclass
 { };

template <template <int...> class C, int ... Is>
class myclass<C<Is...>>
 { };

// ...

template <int ...>
class foo 
 { };

// ...

myclass<foo<0, 1, 2>>  m0; // uses specialization

【讨论】:

  • 模板 class myclass {};模板 类 myclass {};这给了我错误:'myclass':模板参数'Ts'与声明'Ts'不兼容:参数包需要一个类型模板参数
  • @EduardRostomyan - 不兼容,因为该类已声明接收类型列表 (typename...),因此专业化无法直接接收 int 值列表。更多:您将 N 声明为单个 int 值,因此您不能将其 (N...) 扩展为可变参数包。
【解决方案2】:

以下代码是解决您的问题的方法,而不是直接的解决方案。
直接处理参数包可能非常棘手,所以让我们添加一个间接级别。您可以使用另一个模板"wrap" the parameter pack,而不是尝试专门化您的可变参数模板:

#include <type_traits>

template <class... T>
struct wrapper;

// Uses C++17 metafunction for brevity
template <class T, class... Ts>
struct all_same : std::conjunction<std::is_same<T, Ts>...> 
{};

template <class T, class Enable = void>
struct test;

template <template <class...> class Wrapper, class... Ts>
struct test<Wrapper<Ts...>, std::enable_if_t<all_same<Ts...>::value>>
{};

int main()
{
    test<wrapper<int, int>> t;
    //test<wrapper<int, double>> t1; // won't compile, as we haven't defined the primary template
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多