Open In App

std::is_assignable template in C++ with Examples

Last Updated : 28 May, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

The std::is_assignable template of C++ STL is present in the <type_traits> header file. The std::is_assignable template of C++ STL is used to check whether a value of B type can be assigned to a A. It returns the boolean value either true or false. Below is the syntax for the same:

Header File:

#include<type_traits>

Syntax:

template 
  <class A, class B> 
  struct is_assignable;;

Parameters: It accepts the following parameters:

  • A : It represent the type of object that receives the assignment.
  • B : It represent the type of the object that provides the value.

Return Value: The template std::is_assignable(): returns a boolean value i.e either true or false.

Below are the programs to demonstrate std::is_assignable():

Program 1:




// C++ program to illustrate
// is_assignable example
  
#include <bits/stdc++.h>
#include <type_traits>
  
using namespace std;
  
struct A {
};
struct B {
    B& operator=(const A&)
    {
        return *this;
    }
};
  
// Driver Code
int main()
{
    cout << boolalpha;
    cout << "is_assignable:" << endl;
    cout << "A = B: "
         << is_assignable<A, B>::value
         << endl;
    cout << "B = A: "
         << is_assignable<B, A>::value
         << endl;
  
    return 0;
}


Output:

is_assignable:
A = B: false
B = A: true

Program 2:




// C++ program to illustrate
// is_assignable example
  
#include <bits/stdc++.h>
  
#include <type_traits>
  
using namespace std;
  
struct B {
};
struct A {
    A& operator=(const B&)
    {
        return *this;
    }
};
  
// Driver Code
int main()
{
    cout << boolalpha;
    cout << "is_assignable:" << endl;
    cout << "A = B: "
         << is_assignable<A, B>::value
         << endl;
    cout << "B = A: "
         << is_assignable<B, A>::value
         << endl;
  
    return 0;
}


Output:

is_assignable:
A = B: true
B = A: false

Reference: http://www.cplusplus.com/reference/type_traits/is_assignable/



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads