Table of Contents
Basic usage examples
Output result:
Practical application scenarios
Example: Different logic is executed according to the type in the function template
Home Backend Development C++ C std::is_same example

C std::is_same example

Jul 24, 2025 am 03:22 AM
c++

std::is_same is used to determine whether the two types are exactly the same at compile time and return a bool value. 1. In the basic usage, std::is_same::value is true when T and U are exactly the same, otherwise it is false. Different modifiers such as const, reference, pointer, etc. will cause false; 2. You can remove the type modifications and compare them with std::remove_const, std::remove_reference and other types to remove the type modification and then compare them to achieve more flexible type judgment; 3. It is often used in template metaprogramming in practical applications, such as conditional compilation with if constexpr, and different logics are executed according to different types; 4. From C 17, std::is_same_v can be used as the abbreviation of std::is_same::value to improve code readability. This type feature is an important tool for C type safety checking and generic programming.

C std::is_same example

std::is_same is a type trait provided by the <type_traits></type_traits> header file in the C standard library, which is used to determine whether the two types are exactly the same at compile time. It returns a bool value, accessing the result via ::value .

C std::is_same example

Here is a clear example of using std::is_same :


Basic usage examples

 #include <iostream>
#include <type_traits>

int main() {
    std::cout << std::boolalpha; // output true/false instead of 1/0

    //Judge basic type std::cout << "int and int: " 
              << std::is_same<int, int>::value << &#39;\n&#39;; // true

    std::cout << "int and const int: " 
              << std::is_same<int, const int>::value << &#39;\n&#39;; // false

    std::cout << "int and int&: " 
              << std::is_same<int, int&>::value << &#39;\n&#39;; // false

    std::cout << "int and int&&: " 
              << std::is_same<int, int&&>::value << &#39;\n&#39;; // false

    std::cout << "int and double: " 
              << std::is_same<int, double>::value << &#39;\n&#39;; // false

    // Pointer type std::cout << "int* and int*: " 
              << std::is_same<int*, int*>::value << &#39;\n&#39;; // true

    std::cout << "int* and const int*: " 
              << std::is_same<int*, const int*>::value << &#39;\n&#39;; // false

    // Reference type std::cout << "int& and int&: " 
              << std::is_same<int&, int&>::value << &#39;\n&#39;; // true

    // Use remove_const to compare std::cout << "remove_const_t<const int> and int: " 
              << std::is_same<std::remove_const_t<const int>, int>::value << &#39;\n&#39;; // true

    // Use remove_reference to remove reference std::cout << "remove_reference_t<int&> and int: " 
              << std::is_same<std::remove_reference_t<int&>, int>::value << &#39;\n&#39;; // true

    return 0;
}

Output result:

 int and int: true
int and const int: false
int and int&: false
int and int&&: false
int and double: false
int* and int*: true
int* and const int*: false
int& and int&: true
remove_const_t<const int> and int: true
remove_reference_t<int&> and int: true

Practical application scenarios

std::is_same is often used in template metaprogramming, such as:

C std::is_same example
  • Conditional compilation logic (with if constexpr )
  • Overload or specialized templates
  • Type Safety Check

Example: Different logic is executed according to the type in the function template

 #include <iostream>
#include <type_traits>
#include <string>

template<typename T>
void printType(const T& value) {
    if constexpr (std::is_same_v<T, int>) {
        std::cout << "Integer: " << value << &#39;\n&#39;;
    } else if constexpr (std::is_same_v<T, double>) {
        std::cout << "Double: " << value << &#39;\n&#39;;
    } else if constexpr (std::is_same_v<T, std::string>) {
        std::cout << "String: " << value << &#39;\n&#39;;
    } else {
        std::cout << "Unknown type\n";
    }
}

int main() {
    printType(42); // Integer
    printType(3.14); // Double
    printType(std::string{"Hello"}); // String
    return 0;
}

? Note: From C 17, std::is_same_v<t u></t> can be used as the abbreviation of std::is_same<t u>::value</t> .


Basically that's it. std::is_same is one of the cornerstones of type judgment, and it is very flexible to use with other type traits.

C std::is_same example

The above is the detailed content of C std::is_same example. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1505
276
C   find in vector example C find in vector example Aug 02, 2025 am 08:40 AM

The most common method of finding vector elements in C is to use std::find. 1. Use std::find to search with the iterator range and target value. By comparing whether the returned iterator is equal to end(), we can judge whether it is found; 2. For custom types or complex conditions, std::find_if should be used and predicate functions or lambda expressions should be passed; 3. When searching for standard types such as strings, you can directly pass the target string; 4. The complexity of each search is O(n), which is suitable for small-scale data. For frequent searches, you should consider using std::set or std::unordered_set. This method is simple, effective and widely applicable to various search scenarios.

C   char array to string example C char array to string example Aug 02, 2025 am 05:52 AM

The answer is: Use the std::string constructor to convert the char array to std::string. If the array contains the intermediate '\0', the length must be specified. 1. For C-style strings ending with '\0', use std::stringstr(charArray); to complete the conversion; 2. If the char array contains the middle '\0' but needs to convert the first N characters, use std::stringstr(charArray,length); to clearly specify the length; 3. When processing a fixed-size array, make sure it ends with '\0' and then convert it; 4. Use str.assign(charArray,charArray strl

What are the correct launch.json settings for debugging a C   application with GDB on Linux? What are the correct launch.json settings for debugging a C application with GDB on Linux? Aug 04, 2025 am 03:46 AM

TodebugaC applicationusingGDBinVisualStudioCode,configurethelaunch.jsonfilecorrectly;keysettingsincludespecifyingtheexecutablepathwith"program",setting"MIMode"to"gdb"and"type"to"cppdbg",using"ex

C   endianness check example C endianness check example Jul 30, 2025 am 02:30 AM

The system endianness can be detected by a variety of methods, the most commonly used is the union or pointer method. 1. Use a union: Assign uint32_t to 0x01020304, if the lowest address byte is 0x04, it is a small endian, and if it is 0x01, it is a big endian; 2. Use pointer conversion: Assign uint16_t to 0x0102, read the byte order through the uint8_t pointer, [0]==0x02 and [1]==0x01 is a small endian, otherwise it is a big endian; 3. Compilation-time detection: define the constexpr function to determine whether the (char)&int variable is 1, and combine ifconstexpr to determine the endian order during the compilation period; 4. Runtime macro encapsulation: use (char*)&amp

C   mutex example C mutex example Aug 03, 2025 am 08:43 AM

std::mutex is used to protect shared resources to prevent data competition. In the example, the automatic locking and unlocking of std::lock_guard is used to ensure multi-thread safety; 1. Using std::mutex and std::lock_guard can avoid the abnormal risks brought by manual management of locks; 2. Shared variables such as counters must be protected with mutex when modifying multi-threads; 3. RAII-style lock management is recommended to ensure exception safety; 4. Avoid deadlocks and multiple locks in a fixed order; 5. Any scenario of multi-thread access to shared resources should use mutex synchronization, and the final program correctly outputs Expected:10000 and Actual:10000.

What is Succinct (PROVE Coin)? How to operate? PROVE Token Economy and Price Forecast What is Succinct (PROVE Coin)? How to operate? PROVE Token Economy and Price Forecast Aug 06, 2025 pm 06:42 PM

Directory What is Succinct (PROVE) Who created Succinct (PROVE)? Which venture capital supports Succinct (PROVE)? How Succinct (PROVE) works SP1zkVM and Prover network OPSuccinct technology Cross-chain verification PROVE token economics token details Token allocation token utility potential token holders PROVE token price prediction PROVE token pre-market trading activities community prediction of PROVE token price Why choose Succinct? Succ

C   Boost library example C Boost library example Jul 30, 2025 am 01:20 AM

Install the Boost library, 2. Write code for DNS resolution using Boost.Asio, 3. Compile and link the boost_system library, 4. Run the program to output the IP address parsed by www.google.com; this example shows how Boost.Asio simplifies network programming in C, implements cross-platform, type-safe synchronous DNS queries through io_context and tcp::resolver, and supports IPv4 and IPv6 address resolution, and finally prints all resolution results.

C   erase from vector while iterating C erase from vector while iterating Aug 05, 2025 am 09:16 AM

If it is iterating when deleting an element, you must avoid using a failed iterator. ①The correct way is to use it=vec.erase(it), and use the valid iterator returned by erase to continue traversing; ② The recommended "erase-remove" idiom for batch deletion: vec.erase(std::remove_if(vec.begin(),vec.end(), condition), vec.end()), which is safe and efficient; ③ You can use a reverse iterator to delete from back to front, the logic is clear, but you need to pay attention to the condition direction. Conclusion: Always update the iterator with the erase return value, prohibiting operations on the failed iterator, otherwise undefined behavior will result.

See all articles