Aug 20, 2015

[C++11/14] constant expression value can convert to smaller size data structure

#include <initializer_list>
#include <iostream>

using namespace std;

struct Test{
    Test(initializer_list<char> list){
        cout << "IL constructor" << endl;
    }

    Test(int a, char c){
        cout << "general constructor" << endl;
    }
};


template<char c, int i>
void fun(){
    /*
        8.5.4/7:
        A narrowing conversion is an implicit conversion […] from an integer
        type or unscoped enumeration type to an integer type that cannot
        represent all the values of the original type, except where the source
        is a constant expression and the actual value after conversion will
        fit into the target type and will produce the original value when
        converted back to the original type.
    */
    Test{i, c};  // print: IL constructor
}

int main(){
    fun<'^', 3>();
    Test('^', 4);  // print: general constructor
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.