Home>

I want to finish template processing

Problem i am experiencing I'm trying to create a function that doesn't care about

types and numbers.
Specifically, I want to be able to pass the string without worrying about whether it is char or std :: string as in the following source code.
However, if enable_if_t is used, it becomes very redundant, for example, const or not can be separated as follows.
Is there a way to write a function more concisely?

Applicable source code
# include<iostream>
#include<Windows.h>
#include<shellapi.h>
#include<vector>
#include 
#include<string>
#include<type_traits>
using namespace std;

// Is the number increasing too much?
template<typename T, typename U>
enable_if_t<is_same<T, string>:: value&&is_same<U, char *>:: value>cat_str (T str1, U str2)
{
    cout<<str1.length () + strlen (str2)<<endl;
}
template<typename T, typename U>
enable_if_t<is_same<T, char *>:: value&&is_same<U, string>:: value>cat_str (T str1, U str2)
{
    cout<<strlen (str1) + str2.length ()<<endl;
}
template<typename T>
enable_if_t<is_same<T, char *>:: value>cat_str (T str1, T str2)
{
    cout<<str1.length () + str2.length ()<<endl;
}
template<typename T, typename U>
enable_if_t<is_same<T, const char *>:: value&&is_same<U, char *>:: value>cat_str (T str1, U str2)
{
    cout<<strlen (str1) + str2.length ()<<endl;
}
template<typename T, typename U>
enable_if_t<is_same<T, char *>:: value&&is_same<U, const char *>:: value>cat_str (T str1, U str2)
{
    cout<<strlen (str1) + str2.length ()<<endl;
}
template<typename T>
enable_if_t<is_same<T, string>:: value>cat_str (T str1, T str2)
{
    cout<<str1.length () + str2.length ()<<endl;
}

int main () {
    char * str1 = "1234";
    const char * str2 = "5678";
    cat_str (str1, str2);
    char * str3 = "12345";
    string str4 = "67890";
    cat_str (str3, str4);
    const string str5 = "123456";
    string str6 = "789012";
    cat_str (str5, str6);
}
  • Answer # 1

    void cat_str (const string&str1, const string&str2)
    {
        cout<

    I think it's okay

  • Answer # 2

    If it is a solution to the problem that the definition increases in combination explosive, I think that it should be implemented according to the following policy.

    template
    enable_if_t:: value, size_t>get_length (T str) {
        return str.length ();
    }
    template
    enable_if_t:: value, size_t>get_length (T str) {
        return strlen (str);
    }
    template
    void cat_str (const T&str1, const U&str2)
    {
        cout<

  • Answer # 3

    C ++ 17 should use std :: string_view.
    https://cpprefjp.github.io/reference/string_view/basic_string_view.html