Thread: Passing C-style string to template function as reference

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Saying you should use std::array is well and good, but doesn't help the problem here, because we're dealing with string literals. So understanding the intricacies here can be necessary. Often though, you can just provide an overload or template specialization specifically for strings, and avoid the gotcha that way. A non-template overload will always be preferred to a template function, so that can be a way to make sure all strings are treated the same.

    Quote Originally Posted by sythical View Post
    I've managed to figure out what's going on although I'd still appreciate it if someone has anything to add
    Bonus question: What if you do this?
    Code:
    #include <iostream>
    #include <typeinfo>
     
    template <class T1, class T2>
    void f(T1 &x, T2 y)
    {
        T2 z = "baz";
        std::cout << typeid(x).name() << '\n';
        std::cout << typeid(y).name() << '\n';
        std::cout << typeid(z).name() << '\n';
    }
     
    int main()
    {
        f("foo", "bar");
        return 0;
    }
    Do you think the type of z should be "char const *" or "char const[4]"? Try it and see.

    Why it it that way? Because the writers of the standard though this would be most intuitive and useful. As all this demonstrates, array types are treated specially by template type deduction.
    Last edited by King Mir; 01-11-2017 at 05:20 PM.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 09-13-2013, 04:13 PM
  2. Missing reference in function template?
    By Inanna in forum C++ Programming
    Replies: 20
    Last Post: 05-30-2011, 02:26 AM
  3. undefined reference to template function
    By Elkvis in forum C++ Programming
    Replies: 5
    Last Post: 09-02-2009, 08:13 AM
  4. Passing a set to a template function
    By cloudy in forum C++ Programming
    Replies: 1
    Last Post: 10-09-2007, 06:57 AM
  5. template with function-style parameter
    By R.Stiltskin in forum C++ Programming
    Replies: 2
    Last Post: 05-20-2003, 10:56 PM

Tags for this Thread