简体   繁体   中英

Know if template parameter is const char* at compile time?

i want to know at compile time if a template parameter is const char*, example :

static_assert(!is_pointer_to_const_char("test"));

will assert.

Thanks !

Hard-coded string in your example, is not "const char *", but array of "const char[N]". You need to handle this case especially:

template<typename T, std::size_t N>
constexpr bool is_pointer_to_const_char(T(&)[N]) 
{ 
    return std::is_same_v<const char, T>;
}

template<typename T>
constexpr bool is_pointer_to_const_char(T &&) 
{ 
    return std::is_same_v<const char *, T>;
}


int main()
{
    string s1 = "str";

    static_assert(!is_pointer_to_const_char(123)); //NOT ASSERTED
    static_assert(!is_pointer_to_const_char("123")); //ASSERTED!
    static_assert(!is_pointer_to_const_char(s1.c_str())); //ASSERTED!
}

The std::is_same does exactly what you ask:

std::cout << std::is_same<const char*, const char*>::value;
std::cout << std::is_same<const char*, const char>::value;
std::cout << std::is_same<const char*, char*>::value;
std::cout << std::is_same<const char*, const unsigned char*>::value;
std::cout << std::is_same<const char*, const signed char*>::value;
std::cout << std::is_same<const char*, const volatile char*>::value;

The output of this code fragment is 100000 .

There is one caveat with const signed char* and const unsigned char* : these types are not the same as const char* . You decide if that is what you need.

Regarding the usage in template, here is a sample:

template<typename T>
struct C
{
    static int isParametrizedWithConstCharPtr()
    {
        return std:: is_same<const char*, T>::value;
    }
};

std::cout << C<const char*>::isParametrizedWithConstCharPtr(); // 1
std::cout << C<const char>::isParametrizedWithConstCharPtr();  // 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM