【发布时间】:2023-03-24 13:40:01
【问题描述】:
从Using SFINAE to check for global operator<<?和templates, decltype and non-classtypes收集信息,得到如下代码:
基本上,我将两个问题的代码结合起来,如果有 ostream 声明,则调用 print 函数,否则调用 to_string 方法。
取自问题 1
namespace has_insertion_operator_impl {
typedef char no;
typedef char yes[2];
struct any_t {
template<typename T> any_t( T const& );
};
no operator<<( std::ostream const&, any_t const& );
yes& test( std::ostream& );
no test( no );
template<typename T>
struct has_insertion_operator {
static std::ostream &s;
static T const &t;
static bool const value = sizeof( test(s << t) ) == sizeof( yes );
};
}
template<typename T>
struct has_insertion_operator :
has_insertion_operator_impl::has_insertion_operator<T> {
};
取自问题 2
template <typename T>
typename std::enable_if<has_insertion_operator<T>::value, T>::type
print(T obj) {
std::cout << "from print()" << std::endl;
}
template <typename T>
typename std::enable_if<!has_insertion_operator<T>::value, T>::type
print(T obj) {
std::cout << obj.to_string() << std::endl;
}
那我的课是这样的:
struct Foo
{
public:
friend std::ostream& operator<<(std::ostream & os, Foo const& foo);
};
struct Bar
{
public:
std::string to_string() const
{
return "from to_string()";
}
};
并测试输出:
int main()
{
print<Foo>(Foo());
print<Bar>(Bar());
//print<Bar>(Foo()); doesn't compile
//print<Foo>(Bar()); doesn't compile
print(Foo());
print(Bar());
print(42);
print('a');
//print(std::string("Hi")); seg-fault
//print("Hey");
//print({1, 2, 3}); doesn't compile
return 0;
}
print(std::string("Hi")); 线段错误。谁能告诉我为什么?
【问题讨论】:
-
您的代表对您做了什么,以至于您如此急切地分发它? :)
-
@jrok:我感觉到“如何对待好但低代表用户”类型的实验......?
标签: c++ templates segmentation-fault sfinae