c++ - 如果每个参数都可转换为特定类型,则启用构造函数

标签 c++ c++17 typetraits enable-if

只要有多个参数并且每个参数都可转换为类型 value_type,我想启用类 foo 的构造函数。我尝试了以下方法:

struct foo
{
    using value_type = /* some type */;

    template<class... Ts,
        std::enable_if_t<(sizeof...(Ts) > 0) && std::conjunction_v<std::is_convertible_v<Ts, value_type>...>, int> = 0>
    explicit foo(Ts&&... vs)
    {
    }
};

假设 foo::value_type = float。我试图声明 foo bar{ 1 }; 并观察到 ​​ctor 被禁用。为了查看发生了什么,我从模板中删除了 std::conjunction_v 部分并添加了

static_assert(std::conjunction_v<std::is_convertible_v<Ts, value_type>...>, "");

body 。现在我的编译器 (MSVC 14.1/Clang) 产生错误

template argument for template type parameter must be a type

static_assert(std::conjunction_v<std::is_convertible_v<Ts, value_type>...>, "");               
                             // ^

这里到底是什么问题?c

最佳答案

正如声明的那样,模板类型参数的模板参数必须是一个类型。在 std::conjunction<T...> , T s 应该是类型,但是 std::is_convertible_v<X, Y>直接产生值(value)。

试试这个:

std::conjunction_v<std::is_convertible<Ts, value_type>...>
//                                    ^ no `_v`.

顺便说一句,因为你的目标是 C++17,你可以使用 fold expression而不是 std::conjunction :

template<class... Ts,
  std::enable_if_t<((sizeof...(Ts) > 0) && ... && std::is_convertible_v<Ts, value_type>), int> _ = 0
>

关于c++ - 如果每个参数都可转换为特定类型,则启用构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43324057/

相关文章:

c++ - 如果使用constexpr,是否可以删除控制流语句?

c++ - 在编译时计算函数参数

c++ - C++-17 中专门化的模式匹配中 lambda 的拆分函数签名

C++ 模板,将 enable_if 用于运算符的两种不同实现

c++ - 从目标文件中查找函数的所有调用者

c++ - 在 juce 音频应用程序中打印 midi 音符编号

c++ - 为什么变量不是 C++ 中的左值?

C++ 模板类型特征问题

c++ - 模板和多态有什么区别

c++ - CppUtest 在测试之间共享资源, undefined reference