gpt4 book ai didi

C++14 模板偏特化不可见

转载 作者:行者123 更新时间:2023-11-27 23:54:50 25 4
gpt4 key购买 nike

我试图理解为什么模板偏特化变得不可见。

我正在做一个小例子来说明我是如何遇到下面的错误的。该示例试图重载 operator<<打印到 ostream。有一个解决方案适用于问题 1用于打印元组。我的问题是关于为什么下面的那个因不可见错误而失败。

来自 clang 的完整错误:

call to function 'operator<<' that is neither visible in the template definition nor found by argument-dependent
lookup
operator<<(os, std::get<0>(t));
^
testing.cpp:9:47: note: in instantiation of member function 'tuple_printer<1, std::__1::tuple<std::__1::tuple<const char *, int> > >::print'
requested here
tuple_printer<s-1, std::tuple<T...>>::print(os, t);
^
testing.cpp:33:52: note: in instantiation of member function 'tuple_printer<2, std::__1::tuple<const char *, int> >::print' requested here
tuple_printer<sizeof...(T), std::tuple<T...>>::print(os, t);
^
testing.cpp:40:15: note: in instantiation of function template specialization 'operator<<<const char *, int>' requested here
std::cout << std::make_tuple("hello", 5) << std::endl;
^
testing.cpp:30:15: note: 'operator<<' should be declared prior to the call site
std::ostream& operator<<(std::ostream& os, const std::tuple<T...>& t)

示例代码:

#include <tuple>
#include <iostream>

template<size_t s, typename... T>
struct tuple_printer{
static void print(std::ostream& os, const std::tuple<T...>& t){
os << ", ";
os << std::get<s-1>(t);
tuple_printer<s-1, std::tuple<T...>>::print(os, t);
}
};

template<typename... T>
struct tuple_printer<0, T...>{
static void print(std::ostream& os, const std::tuple<T...>& t){
//nothing to do here
}
};

template<typename... T>
struct tuple_printer<1, T...>{
static void print(std::ostream& os, const std::tuple<T...>& t){
//no need for comma separator
os << std::get<0>(t);
}
};

template <typename... T>
std::ostream& operator<<(std::ostream& os, const std::tuple<T...>& t)
{
os << "[";
tuple_printer<sizeof...(T), std::tuple<T...>>::print(os, t);
return os << "]";
}

int main()
{
std::cout << std::make_tuple(2, 3.14159F, 2345.678) << std::endl;
std::cout << std::make_tuple("hello", 5) << std::endl;
std::cout << std::make_tuple() << std::endl;
return 0;
}

最佳答案

1. tuple_printer不带size_t, tuple<T...>但是size_t, T... :

替换tuple_printer<s-1, std::tuple<T...>>与:

tuple_printer<s-1, T...>

tuple_printer<sizeof...(T), std::tuple<T...>>与:

tuple_printer<sizeof...(T), T...>

2. 此外,我猜您希望基本模板中的语句顺序有所不同:

tuple_printer<s-1, T...>::print(os, t);
os << ", ";
os << std::get<s-1>(t);

关于C++14 模板偏特化不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43301335/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com