【问题标题】:static_assert referencing enclosing template classstatic_assert 引用封闭模板类
【发布时间】:2017-11-21 20:35:34
【问题描述】:

在以下代码中,VS2015 在IsInstantiation<OtherType, T1>::value 抱怨,给出此错误“模板参数'TT' 的模板参数无效,需要类模板”。我将如何解决这个问题?我想将 OtherType 限制为 T1 枯萎 SomeTypeOtherType 的情况。

template <template<typename...> class TT, typename T>
struct IsInstantiation : std::false_type
{
};

template <template<typename...> class TT, typename... Ts>
struct IsInstantiation<TT, TT<Ts...>> : std::true_type
{
};

template <typename T1>
class SomeType{};

template <typename T1, typename T2>
class OtherType
{
    static_assert(IsInstantiation<SomeType, T1>::value ||
        IsInstantiation<OtherType, T1>::value,
        "Event must have SomeType or OtherType as first type");
public:
    explicit OtherType(T1 t1, T2 t2)
        : mT1{ std::move(t1) }
        , mT2{ std::move(t2) }
    {
    }

private:
    T1 mT1;
    T2 mT2;
};

【问题讨论】:

  • 哪个是“二次使用”?可以标记一下吗?
  • Barry 改进了我的答案。

标签: c++ c++11 c++14 c++17 variadic-templates


【解决方案1】:

试试

template <typename, typename>
class OtherType;

template <typename T1, typename T2>
using OtherTypeAlias = OtherType<T1, T2>;

template <typename T1, typename T2>
class OtherType
{
    static_assert(IsInstantiation<SomeType, T1>::value ||
        IsInstantiation<OtherTypeAlias, T1>::value,
        "Event must have SomeType or OtherType as first type");

问题:OtherType里面,写OtherType的时候,默认是OtherType&lt;T1, T2&gt;;因此,当您将OtherType 作为IsIstantiation 的参数传递时,您传递的是模板类型,而不是模板模板。

-- 编辑--

我不知道,但可以直接引用 OtherType 中的干(没有模板默认参数)(感谢 Barry!)。

这样就简单多了

O 不知道如何直接引用 OtherType 类 -- 作为模板模板,没有默认模板参数 -- 在 OtherType 的正文中

template <typename T1, typename T2>
class OtherType
{
    static_assert(IsInstantiation<SomeType, T1>::value ||
        IsInstantiation<::OtherType, T1>::value,
        "Event must have SomeType or OtherType as first type");

没有别名

【讨论】:

  • ::OtherType
  • @Barry - 我不知道的部分(但我不得不想象);谢谢。
  • 无论如何这是一个错误。根据 [temp.local]/1,injected-class-name 应该被视为在此上下文中引用类模板。
  • @T.C. - 对不起;不确定是否理解;你的意思是问题中的代码是正确的,并且是 VS2015 的错误(还有我的 clang++)?
  • 是的,@T.C.意味着符合标准的编译器应该接受您的原始程序。 (godbolt.org/g/CK524M)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
  • 2021-03-14
  • 2021-06-14
  • 1970-01-01
  • 2023-01-10
  • 2013-07-14
相关资源
最近更新 更多