【问题标题】:Syntax error for template struct instantiation inside assert statement断言语句中模板结构实例化的语法错误
【发布时间】:2021-05-05 16:06:24
【问题描述】:

对于以下在标头中定义的模板结构:

#include <unordered_set>

namespace Utilities::ContainerHelpers
{
    template <template <class> class TContainer, class TVal>
    struct is_unique
    {
        bool operator()(TContainer<TVal> const& container) const
        {
            std::unordered_set<TVal, typename TVal::HashFunc> 
                uniqueSubset(container.begin(), container.end());

            return container.size() == uniqueSubset.size();
        }
    };
}

在断言上下文中使用时出现语法错误:

assert(Utilities::ContainerHelpers::is_unique< std::vector, TelemDetail >{}(telem_detail_obj);

但不是在断言之外定义为临时的。 TelemDetail 类型并不重要,只是包含一个嵌套的 HashFunc 结构类型。

警告 C4002:函数式宏调用“断言”的参数过多

错误 C2059:语法错误:')'

感觉我遗漏了一些明显的东西?使用 MSVC 2019 编译 -std=c++17

【问题讨论】:

  • msvc but fails on gcc and clang 上编译。所以缺少一些信息。
  • 如果我将 assert 参数包装在另一组括号内似乎可以工作,但我不知道为什么?
  • 如果您想让其他人知道原因,您需要显示minimal reproducible example
  • @M.A 你没抓住重点。您应该发布尽可能重现该问题的代码。我们不应该有重现问题的问题。无论如何,PiotrNycz 能够填补空白并提供了答案。
  • 可以进行更多改进:在参数中使用可变参数:template &lt;class...&gt; class TContainer - 例如std::vector 有两个参数 - 不仅仅是一个(第二个默认为 std::allocator&lt;T&gt;)。

标签: c++ templates syntax-error


【解决方案1】:

assert,作为每个宏,不理解C++,它把每个逗号,当作参数分隔符:

assert(is_unique< std::vector, TelemDetail >{}(session_details));
//    (   first arg          ,  second arg                     )
//                                   

但预处理器宏“理解”() - 所以只需添加额外的一对()

assert((is_unique&lt; std::vector, TelemDetail &gt;{}(session_details)));

【讨论】:

  • “逗号”,而不是“冒号”
猜你喜欢
  • 2021-12-01
  • 1970-01-01
  • 2011-12-28
  • 1970-01-01
  • 2021-12-16
  • 1970-01-01
  • 2017-10-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多