user1899020
user1899020

Reputation: 13575

How to make initializer list implicitly convert to the class?

For example, I have a class

struct A
{
    A(int i, double d) {...}

private:
    int m_i;
    double m_d; 
};

and a function with an argument A

void f(A a);

And I can use initializer list to call the function

f( A{1, 3.14} );

How to make the following simple version also works?

f( {1, 3.14} );

Upvotes: 5

Views: 478

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311018

The call of the function with the initializer list will work. You should do nothing special.:)

The call would not be compiled if the constructor had function specifier explicit. In this case you have to use the previous call of the function

f( A{1, 3.14} );

using functional notation of casting the initializer list to an object of type A.

Upvotes: 6

uchar
uchar

Reputation: 2590

If you have multiple overload of a function which accept objects with same constructor and you want f( {1, 3.14} ); call one of them

It's possible with some meta programming

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

struct A{
     A(int ,double) {}
};

struct B{
     B(int ,double) {}
};

template<class T=A>
void f(T a,
       typename std::enable_if<std::is_same<T,A>::value>::type* = 0 ){
    std::cout<<"In f(A a)\n";
}

void f(B b){std::cout<<"In f(B b)\n";}

int main(int argc, char**argv)
{
    f({1,2}); //It's not ambiguity anymore and calls f(B a)
    f(A{1,2});//call f(A a)
    f(B{1,2});//call f(B b)
    //f(2); error
}

live

Upvotes: 0

Related Questions