INT = 0的模板专业化

发布于 2025-01-21 07:15:05 字数 1265 浏览 5 评论 0原文

我想实现自己的STD ::元组,而无需查看官方实现,但我会遇到C2768错误(Visual Studio)。

我读过的编译器不知道这是模板专业化还是函数的全新定义,但我不知道它将如何认为这是一个新功能

#include <iostream>

template<class T, class... Ts>
struct _tuple_node {
    T value;
    _tuple_node<Ts...> next;

    constexpr _tuple_node(T value, Ts... rest) : value(value), next(rest...) {
    }
};

template<class T>
struct _tuple_node<T> {
    T value;
    
    constexpr _tuple_node(T value) : value(value) {
    }
};

template<class... Ts> 
struct tuple {
    _tuple_node<Ts...> first;

    constexpr tuple(Ts... args) : first(args...) {
    }
};

template<int i, class T, class... Ts>
auto _get_t(_tuple_node<T, Ts...>& t) {
    return _get_t<i - 1, Ts...>(t.next);
}

template<class T, class... Ts>
auto _get_t<0, T, Ts...>(_tuple_node<T, Ts...>& t) {  //here
    return t.value;
}

template<int i, class T>
auto _get_t(_tuple_node<T>& t) {
    return t.value;
}

template<int i, class... Ts>
auto get(tuple<Ts...>& t) {
    return _get_t<i>(t.first);
}


int main() {
    tuple foo(1, std::string("test"));

    std::cout << get<0>(foo);
}

I want to implement my own std::tuple, without looking into an official implementation, but I'm getting a C2768 error (visual studio).

I've read compilator doesn't know if this is a template specialization or a completely new definition of a function, but I don't know how it would assume this is a new function

#include <iostream>

template<class T, class... Ts>
struct _tuple_node {
    T value;
    _tuple_node<Ts...> next;

    constexpr _tuple_node(T value, Ts... rest) : value(value), next(rest...) {
    }
};

template<class T>
struct _tuple_node<T> {
    T value;
    
    constexpr _tuple_node(T value) : value(value) {
    }
};

template<class... Ts> 
struct tuple {
    _tuple_node<Ts...> first;

    constexpr tuple(Ts... args) : first(args...) {
    }
};

template<int i, class T, class... Ts>
auto _get_t(_tuple_node<T, Ts...>& t) {
    return _get_t<i - 1, Ts...>(t.next);
}

template<class T, class... Ts>
auto _get_t<0, T, Ts...>(_tuple_node<T, Ts...>& t) {  //here
    return t.value;
}

template<int i, class T>
auto _get_t(_tuple_node<T>& t) {
    return t.value;
}

template<int i, class... Ts>
auto get(tuple<Ts...>& t) {
    return _get_t<i>(t.first);
}


int main() {
    tuple foo(1, std::string("test"));

    std::cout << get<0>(foo);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文