c++ - 继承CTAD构造函数

标签 c++ c++17 stdtuple ctad

我从 std::tuple 派生,但由于类模板参数推导问题,无法从初始值设定项列表构造派生类。除了给它一个已经构造好的元组 first{ std::tuple{1, 1.0f, 1u} }; .

之外,还有更好的方法来构造这样的类吗?
template <typename T, typename... Types>
struct first : public std::tuple<T, Types...>
{
    //using std::tuple<T, Types...>::tuple;
    template<typename F>
        requires std::invocable<F, T>
    auto transform(F f)
    {
        auto result = *this;
        std::get<0>(result) = f(std::get<0>(result));
        return result;
    }
};

int main()
{
    //auto tuple = first{ 1, 1.0f, 1u };
    auto tuple = first{ std::tuple{1, 1.0f, 1u} };
    auto tuple2 = tuple.transform([](auto a) {return a + 3; });
}

最佳答案

继承的构造函数不是 CTAD 的一部分。

您可以复制std::tuple's CTAD :

template <typename T, typename... Types>
first(T, Types...) -> first<T, Types...>;

// auto tuple = first{1, 1.0f, 1u}; // is ok now
// auto tuple = first{ std::tuple{1, 1.0f, 1u} }; // broken now

Demo

关于c++ - 继承CTAD构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73147898/

相关文章:

c++ - 无法显示具有添加的 warpPerspective 功能的 OpenCV/sample/cpp/lkdemo.cpp 的图像

c++ - 使用 share_from_this 而不是 this 指针

c++ - 我可以将新的 std::tuple 放入内存映射区域,然后再读回吗?

c++ - C++/CX 中的 [this] 是什么? (Windows 8)

c++ - C++中运算符和函数的区别?

c++ - 通过构造函数进行依赖注入(inject)的最佳实践

c++ - 如何实现通用 switch/case,它也适用于一般 C++ 类型并且语法相似?

用于 string_view 的 C++17 运算符?

c++ - 如何扩展元组以匹配提供的参数?

c++ - 在 Ubuntu 14.04 上使用 GCC v4.8 在 C++11 中定义元组 vector 时出现编译错误