c++ - `static_assert` 如何在成员初始值设定项列表中构造模板类?

标签 c++ c++17 template-meta-programming static-assert stdinitializerlist

我有MyClass这是一个模板类。我想提供一个初始化 r 列表构造函数,以便我可以方便地编写:

MyClass<int> Arr0{ 1,  2,  3, 4, 5, 8 };

另一方面,我不想在此列表中出现重复项,因为此类仅具有唯一的用户输入。我已经看到了很多检查数组中重复项的方法,我想出了 has_duplicates()以下功能。

我尝试结合检查的想法,是否 std::initializer_list<T> ed 临时元素(或数组)包含成员初始值设定项列表本身中的任何重复元素; 如果包含static_assert()模板实例化,因此不会构造此类的任何对象。

以下是我的代码的最小示例。

#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <iterator>
#include <initializer_list>

template <typename Iterator> // function to check duplicates(which works fine)
constexpr bool has_duplicates(Iterator start, Iterator end)
{
    if (start == end) return false;
    using Type = typename std::remove_reference_t<decltype(*end)>;
    std::map<Type, std::size_t> countMap;
    for (; start != end; ++start)
    {
        countMap[*start]++;
        if (countMap[*start] >= 2) return true;
    }
    return false;
}

template <typename T> class MyClass
{
private:
    std::vector<T> m_vec;

public:
    MyClass(std::initializer_list<T> a)
        : (has_duplicates(a.begin(), a.end()) //-----> here is the problem
            ? static_assert(false, " the array has duplicates....")
            : m_vec(a)
           )
    {
        std::cout << "Constriction successful....";
    }
};

int main()
{
    std::vector<int> test{ 1, 2, 3, 4, 1 };
    std::cout << std::boolalpha 
        << has_duplicates(test.begin(), test.end()) << std::endl; // works
    MyClass<int> Arr0{ 1,  2,  3, 4 }; // error
    return 0;
}

在 MSVC 16.0(C++17 标志)中编译时,出现错误:

error C2059: syntax error: 'static_assert'
note: while compiling class template member function 'MyClass<int>::MyClass(std::initializer_list<_Ty>)'
      with
      [
          _Ty=int
      ]
note: see reference to function template instantiation 'MyClass<int>::MyClass(std::initializer_list<_Ty>)' being compiled
      with
      [
          _Ty=int
      ]
note: see reference to class template instantiation 'MyClass<int>' being compiled
error C2143: syntax error: missing ';' before '}'
error C2059: syntax error: ')'
error C2447: '{': missing function header (old-style formal list?)

它说一个简单的语法错误,但我没有看到任何按照 static_assert 的错误。 .

谁能帮我找出错误吗?

防止std::initializer_list<T>施工的正确方法是什么?在上述情况下,构造函数参数?

最佳答案

你想要做的,一个静态断言来检查构造函数的参数,是(据我所知)根本不可能的。

static_assert() 在编译时工作,其中 MyClass 对象在运行时初始化(可以初始化)。

我能想象到的最好的就是一个 make_MyClass() 函数,它接收参数列表作为模板参数

template <auto v0, auto ... vs>
auto make_MyClass ()
 {
   static_assert( false == has_duplicates<v0, vs...>() );

   return MyClass<decltype(v0)>{ v0, vs... };
 }

因此您可以执行static_assert(),因为现在您知道编译时的值;我重写了 has_duplicates() 函数,如下所示,因为您的原始函数无法有效地 constexpr (因为 std::map 不是t)

template <typename = void>
constexpr bool has_duplicates ()
 { return false; }

template <auto v0, auto ... vs>
constexpr bool has_duplicates ()
 { return ((v0 == vs) || ... ) || has_duplicates<vs...>(); }

以下是完整的编译示例

#include <iostream>
#include <vector>
#include <initializer_list>

template <typename = void>
constexpr bool has_duplicates ()
 { return false; }


template <auto v0, auto ... vs>
constexpr bool has_duplicates ()
 { return ((v0 == vs) || ... ) || has_duplicates<vs...>(); }  

template <typename T> class MyClass
{
private:
    std::vector<T> m_vec;

public:
    MyClass(std::initializer_list<T> a) : m_vec{a}
     { std::cout << "Constriction successful...."; }
};

template <auto v0, auto ... vs>
auto make_MyClass ()
 {
   static_assert( false == has_duplicates<v0, vs...>() );

   return MyClass<decltype(v0)>{ v0, vs... };
 }

int main ()
 {
    std::cout << std::boolalpha 
        << has_duplicates<1, 2, 3, 4, 1>() << std::endl;

    auto mc0 = make_MyClass<1, 2, 3, 4, 5>(); // compile
    //auto mc1 = make_MyClass<1, 2, 3, 4, 1>(); // static_assert error
 }

关于c++ - `static_assert` 如何在成员初始值设定项列表中构造模板类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55996035/

相关文章:

c++ - 如何为类特定的 typedef (c++17) 启用自动类型推导?

c++ - 在 C++ 中获取依赖于模板的模板类型

c++ - 使用参数包参数初始化 `std::array`

具有默认参数的 C++ 模板类,可能还有元编程

c++ - 调色板图像需要有效的调色板

c++ - 如何在 spidermonkey 嵌入中提供 js-ctypes?

c++ - 为什么 std::function 没有进行类型检查?

c++ - 将重载的 CRTP 类成员方法传递给 lambda

C++ ⎼ 两个相似的函数,但表现却大不相同

c++ - 在 C++ 中,相等运算符中两个 = 之间的空格是否合法?