Note that there are some explanatory texts on larger screens.

plurals
  1. POtype_traits segmentation fault with std::string
    primarykey
    data
    text
    <p>Gathering the information from <a href="https://stackoverflow.com/questions/5768511/using-sfinae-to-check-for-global-operator">Using SFINAE to check for global operator&lt;&lt;?</a> and <a href="https://stackoverflow.com/questions/16505621/templates-decltype-and-non-classtypes">templates, decltype and non-classtypes</a>, I got the following code:</p> <p><a href="http://ideone.com/sEQc87" rel="nofollow noreferrer">http://ideone.com/sEQc87</a></p> <p>Basically I combined the code from both questions to call <code>print</code> function if it has <code>ostream</code> declaration, or to call the <code>to_string</code> method otherwise.</p> <p><strong>Taken from question 1</strong></p> <pre><code>namespace has_insertion_operator_impl { typedef char no; typedef char yes[2]; struct any_t { template&lt;typename T&gt; any_t( T const&amp; ); }; no operator&lt;&lt;( std::ostream const&amp;, any_t const&amp; ); yes&amp; test( std::ostream&amp; ); no test( no ); template&lt;typename T&gt; struct has_insertion_operator { static std::ostream &amp;s; static T const &amp;t; static bool const value = sizeof( test(s &lt;&lt; t) ) == sizeof( yes ); }; } template&lt;typename T&gt; struct has_insertion_operator : has_insertion_operator_impl::has_insertion_operator&lt;T&gt; { }; </code></pre> <p><strong>Taken from question 2</strong></p> <pre><code>template &lt;typename T&gt; typename std::enable_if&lt;has_insertion_operator&lt;T&gt;::value, T&gt;::type print(T obj) { std::cout &lt;&lt; "from print()" &lt;&lt; std::endl; } template &lt;typename T&gt; typename std::enable_if&lt;!has_insertion_operator&lt;T&gt;::value, T&gt;::type print(T obj) { std::cout &lt;&lt; obj.to_string() &lt;&lt; std::endl; } </code></pre> <p>Then my classes are like so:</p> <pre><code>struct Foo { public: friend std::ostream&amp; operator&lt;&lt;(std::ostream &amp; os, Foo const&amp; foo); }; struct Bar { public: std::string to_string() const { return "from to_string()"; } }; </code></pre> <p>And test output:</p> <pre><code>int main() { print&lt;Foo&gt;(Foo()); print&lt;Bar&gt;(Bar()); //print&lt;Bar&gt;(Foo()); doesn't compile //print&lt;Foo&gt;(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; } </code></pre> <p>The <code>print(std::string("Hi"));</code> line seg-faults. Can anyone tell me why?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload